Advertisement
Guest User

Untitled

a guest
Nov 12th, 2019
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.94 KB | None | 0 0
  1. import java.io.*;
  2. import java.net.ServerSocket;
  3. import java.net.Socket;
  4. import java.util.zip.ZipEntry;
  5. import java.util.zip.ZipFile;
  6. import java.util.zip.ZipInputStream;
  7. import java.util.zip.ZipOutputStream;
  8.  
  9. public class Main {
  10.  
  11. public static void main(String[] args) throws InterruptedException {
  12.  
  13. /*try (ServerSocket server = new ServerSocket(3345)) {
  14.  
  15. Socket client = server.accept();
  16.  
  17. System.out.println("Connection accepted.");
  18.  
  19. OutputStream out = new FileOutputStream("/../../home/denis/IdeaProjects/ParserHSE/out/production/ParserHSE/sample/gifs/giphy123.gif");
  20. System.out.println("DataOutputStream created");
  21.  
  22.  
  23. DataInputStream in = new DataInputStream(client.getInputStream());
  24. System.out.println("DataInputStream created");
  25.  
  26. //while(!client.isClosed()) {
  27. System.out.println("Server reading from channel");
  28.  
  29. int count = in.readInt();
  30. System.out.println(count);
  31. byte[] bytes = new byte[count];
  32. if(count > 1){
  33. //bytes = new byte[count];
  34. in.read(bytes, 0, count);
  35. }
  36.  
  37.  
  38. *//*byte[] buffer = new byte[8192];
  39.  
  40. while ((count = in.read(buffer)) > 0) {
  41. out.write(buffer, 0, count);
  42. System.out.println("qweqweqwe");
  43. }*//*
  44.  
  45. try (FileOutputStream fos = new FileOutputStream("/../../home/denis/IdeaProjects/ParserHSE/out/production/ParserHSE/sample/gifs/giphy123.gif")) {
  46. fos.write(bytes);
  47. }
  48. //out.flush();
  49. //}
  50.  
  51. in.close();
  52. out.close();
  53. client.close();
  54. System.out.println("Closing connections & channels - DONE.");
  55.  
  56. } catch (IOException e) {
  57. e.printStackTrace();
  58. }*/
  59. try (ServerSocket server= new ServerSocket(3345);){
  60. // становимся в ожидание подключения к сокету под именем - "client" на серверной стороне
  61. Socket client = server.accept();
  62.  
  63. // после хэндшейкинга сервер ассоциирует подключающегося клиента с этим сокетом-соединением
  64. System.out.print("Connection accepted.");
  65.  
  66. // инициируем каналы общения в сокете, для сервера
  67.  
  68. // канал чтения из сокета
  69. InputStream in = (client.getInputStream());
  70. System.out.println("DataInputStream created");
  71.  
  72. // канал записи в сокет
  73. OutputStream out = new FileOutputStream("/../../home/denis/IdeaProjects/ParserHSE/out/production/ParserHSE/sample/gifs/giphy123.gif");
  74. System.out.println("DataOutputStream created");
  75.  
  76. // начинаем диалог с подключенным клиентом в цикле, пока сокет не закрыт
  77. while(!client.isClosed()){
  78.  
  79. System.out.println("Server reading from channel");
  80.  
  81. // сервер ждёт в канале чтения (inputstream) получения данных клиента
  82.  
  83.  
  84. byte[] bytes = new byte[558095];
  85. int count;
  86. while ((count = in.read(bytes)) > 0) {
  87. out.write(bytes, 0, count);
  88. }
  89. //out.flush();
  90.  
  91. //if(count > 1){
  92. //bytes = new byte[count];
  93. //System.out.println(in.read(bytes, 0, 558095) + "sdf");
  94. //}
  95. //String entry = in.readUTF();
  96.  
  97. // после получения данных считывает их
  98. // System.out.println("READ from client message - "+entry);
  99.  
  100. // и выводит в консоль
  101. System.out.println("Server try writing to channelfftghfthrftgh");
  102.  
  103. // инициализация проверки условия продолжения работы с клиентом по этому сокету по кодовому слову
  104.  
  105. // если условие окончания работы не верно - продолжаем работу - отправляем эхо обратно клиенту
  106. //out.writeUTF("Server reply - "+entry + " - OK");
  107. /*try (FileOutputStream stream = new FileOutputStream("/../../home/denis/IdeaProjects/ParserHSE/out/production/ParserHSE/sample/gifs/giphy123.gif")) {
  108. stream.write(bytes);
  109. }*/
  110. System.out.println("Server Wrote message to client.");
  111.  
  112. // освобождаем буфер сетевых сообщений
  113. //out.flush();
  114.  
  115. }
  116.  
  117. // если условие выхода - верно выключаем соединения
  118. System.out.println("Client disconnected");
  119. System.out.println("Closing connections & channels.");
  120.  
  121. // закрываем сначала каналы сокета !
  122. in.close();
  123. out.close();
  124.  
  125. // потом закрываем сокет общения на стороне сервера!
  126. client.close();
  127.  
  128. // потом закрываем сокет сервера который создаёт сокеты общения
  129. // хотя при многопоточном применении его закрывать не нужно
  130. // для возможности поставить этот серверный сокет обратно в ожидание нового подключения
  131. server.close();
  132. System.out.println("Closing connections & channels - DONE.");
  133. } catch (IOException e) {
  134. e.printStackTrace();
  135. }
  136. }
  137. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement