Advertisement
vanillajelly

Untitled

Jun 27th, 2019
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.28 KB | None | 0 0
  1. import java.io.*;
  2. import java.net.*;
  3. import java.util.*;
  4. public class MultiTransferServerA
  5. {
  6. private static ServerSocket serverSocket;
  7. private static final int PORT = 1234;
  8. public static void main(String[] args)
  9. throws IOException
  10. {
  11. try
  12. {
  13. serverSocket = new ServerSocket(PORT);
  14. }
  15. catch (IOException ioEx)
  16. {
  17. System.out.println("\nUnable to set up port!");
  18. System.exit(1);
  19. }
  20. do
  21. {
  22. //Wait for client...
  23. Socket client = serverSocket.accept();
  24. System.out.println("\nNew client accepted.\n");
  25. //Create a thread to handle communication with
  26. //this client and pass the constructor for this
  27. //thread a reference to the relevant socket...
  28. ClientHandler handler =
  29. new ClientHandler(client);
  30. handler.start();//As usual, method calls run.
  31. }while (true);
  32. }
  33. }
  34. class ClientHandler extends Thread
  35. {
  36. Socket socket = null;
  37. InputStream input = null;
  38. OutputStream output = null;
  39. public ClientHandler(Socket socket) throws IOException
  40. {
  41. //Set up reference to associated socket...
  42. try {
  43. input = socket.getInputStream();
  44. } catch (IOException ex) {
  45. System.out.println("Can't get socket input stream. ");
  46. }
  47.  
  48. try {
  49. output = new FileOutputStream("A:\\TerimaBdariA .png");
  50. } catch (FileNotFoundException ex) {
  51. System.out.println("File not found. ");
  52. }
  53.  
  54.  
  55. byte[] bytes = new byte[16*1024];
  56.  
  57. int count;
  58. while ((count = input.read(bytes)) > 0) {
  59. output.write(bytes, 0, count);
  60. }
  61.  
  62. System.out.println("File received.");
  63.  
  64. output.close();
  65. input.close();
  66. }
  67. public void run()
  68. {
  69. String received;
  70.  
  71. try
  72. {
  73. if (socket!=null)
  74. {
  75. System.out.println(
  76. "Closing down connection...");
  77. socket.close();
  78. }
  79. }
  80. catch(IOException ioEx)
  81. {
  82. System.out.println("Unable to disconnect!");
  83. }
  84. }
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement