Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package server;
- import java.io.BufferedReader;
- import java.io.DataOutputStream;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.PrintWriter;
- import java.net.Socket;
- public class ConnectionHandler implements Runnable {
- Socket connection;
- private File dir;
- public ConnectionHandler(Socket connection, File dir) {
- this.connection = connection;
- this.dir = dir;
- }
- @Override
- public void run() {
- try {
- BufferedReader in = new BufferedReader(new InputStreamReader(
- connection.getInputStream()));
- DataOutputStream out = new DataOutputStream( connection.getOutputStream() );
- PrintWriter outprinter = new PrintWriter(out);
- do {
- String commandline = in.readLine();
- if (commandline == null) {
- // connection was closed
- out.close();
- in.close();
- break;
- }
- String command = commandline.substring(0, commandline.indexOf(' '));
- String args = commandline.substring(commandline.indexOf(' '));
- if(command=="!download") {
- // first get the file
- try {
- File requestedfile = new File(dir,args);
- FileInputStream fis = new FileInputStream(requestedfile);
- out.writeLong( requestedfile.length() ); // write the length if file was found and will be transmitted
- // start block copy
- byte[] buf = new byte[1024];
- int len;
- while ((len = fis.read(buf)) > 0){
- out.write(buf, 0, len);
- }
- outprinter.println("");
- outprinter.println("upload finished");
- } catch (IOException e) {
- System.err.println("error opening requested file");
- out.writeLong(-1);
- e.printStackTrace();
- }
- }
- } while (true);
- } catch (IOException e) {
- System.err.println("error handling connection");
- e.printStackTrace();
- }
- }
- }
Add Comment
Please, Sign In to add comment