Guest User

Untitled

a guest
Jun 19th, 2018
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.84 KB | None | 0 0
  1. package server;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.DataOutputStream;
  5. import java.io.File;
  6. import java.io.FileInputStream;
  7. import java.io.IOException;
  8. import java.io.InputStreamReader;
  9. import java.io.PrintWriter;
  10. import java.net.Socket;
  11.  
  12. public class ConnectionHandler implements Runnable {
  13. Socket connection;
  14. private File dir;
  15.  
  16. public ConnectionHandler(Socket connection, File dir) {
  17. this.connection = connection;
  18. this.dir = dir;
  19. }
  20.  
  21. @Override
  22. public void run() {
  23. try {
  24. BufferedReader in = new BufferedReader(new InputStreamReader(
  25. connection.getInputStream()));
  26. DataOutputStream out = new DataOutputStream( connection.getOutputStream() );
  27.  
  28. PrintWriter outprinter = new PrintWriter(out);
  29. do {
  30. String commandline = in.readLine();
  31. if (commandline == null) {
  32. // connection was closed
  33. out.close();
  34. in.close();
  35. break;
  36. }
  37. String command = commandline.substring(0, commandline.indexOf(' '));
  38. String args = commandline.substring(commandline.indexOf(' '));
  39.  
  40.  
  41. if(command=="!download") {
  42. // first get the file
  43. try {
  44. File requestedfile = new File(dir,args);
  45. FileInputStream fis = new FileInputStream(requestedfile);
  46.  
  47. out.writeLong( requestedfile.length() ); // write the length if file was found and will be transmitted
  48.  
  49. // start block copy
  50. byte[] buf = new byte[1024];
  51. int len;
  52. while ((len = fis.read(buf)) > 0){
  53. out.write(buf, 0, len);
  54. }
  55. outprinter.println("");
  56. outprinter.println("upload finished");
  57.  
  58. } catch (IOException e) {
  59. System.err.println("error opening requested file");
  60. out.writeLong(-1);
  61. e.printStackTrace();
  62. }
  63. }
  64.  
  65. } while (true);
  66.  
  67. } catch (IOException e) {
  68. System.err.println("error handling connection");
  69. e.printStackTrace();
  70. }
  71. }
  72.  
  73. }
Add Comment
Please, Sign In to add comment