ungureanuvladvictor

Untitled

Dec 6th, 2013
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.30 KB | None | 0 0
  1. package com.vungueanu;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.File;
  5. import java.io.FileReader;
  6. import java.io.IOException;
  7. import java.io.InputStreamReader;
  8. import java.io.PrintWriter;
  9. import java.net.Socket;
  10.  
  11. public class doComms implements Runnable {
  12.  
  13. private File directory = null;
  14. private Socket connection = null;
  15. private BufferedReader incoming = null;
  16. private PrintWriter outgoing = null;
  17.  
  18. /**
  19. * Makes conn and starts the thread
  20. * @param directory
  21. * @param connection
  22. */
  23. doComms (File directory, Socket connection) {
  24. this.directory = directory;
  25. this.connection = connection;
  26. System.out.println("New connection!\n");
  27. (new Thread(this)).start();
  28. }
  29.  
  30. /**
  31. * Sends the names of the files over the connection
  32. */
  33. private void index () {
  34. String[] fileList = directory.list();
  35. for (int i = 0; i < fileList.length; ++i)
  36. outgoing.println(fileList[i]);
  37.  
  38. outgoing.flush();
  39. outgoing.close();
  40. }
  41.  
  42. /**
  43. * Sends the file requested
  44. * @param fileName the file
  45. * @throws IOException
  46. */
  47. private void send (String fileName) throws IOException {
  48. File file = new File(directory, fileName);
  49.  
  50. if (!file.exists() || file.isDirectory()) {
  51. outgoing.println("Error with the file!");
  52. }
  53. else {
  54. //outgoing.println("OK!");
  55. BufferedReader in = new BufferedReader (new FileReader (file));
  56. String line = "";
  57. while ((line = in.readLine()) != null) {
  58. outgoing.println(line);
  59. }
  60.  
  61. outgoing.flush();
  62. outgoing.close();
  63.  
  64. in.close();
  65. }
  66. }
  67.  
  68. @Override
  69. public void run() {
  70. String command = "";
  71.  
  72. try {
  73. incoming = new BufferedReader (new InputStreamReader (connection.getInputStream()));
  74. outgoing = new PrintWriter (connection.getOutputStream() );
  75.  
  76. command = incoming.readLine();
  77.  
  78. if (command.equals("index")) {
  79. this.index();
  80. return;
  81. }
  82. else if (command.startsWith("get")) {
  83. String fileName = command.substring(3).trim();
  84. this.send (fileName);
  85. }
  86. else {
  87. outgoing.println("Unknown command\n");
  88. outgoing.flush();
  89. }
  90.  
  91. } catch (IOException e) {
  92. System.out.println("Error with command " + command + "\n");
  93. } finally {
  94. try {
  95. connection.close();
  96. } catch (IOException e) {
  97. e.printStackTrace();
  98. }
  99. }
  100. }
  101. }
Advertisement
Add Comment
Please, Sign In to add comment