Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.net.ServerSocket;
- import java.net.Socket;
- import java.util.zip.ZipEntry;
- import java.util.zip.ZipFile;
- import java.util.zip.ZipInputStream;
- import java.util.zip.ZipOutputStream;
- public class Main {
- public static void main(String[] args) throws InterruptedException {
- /*try (ServerSocket server = new ServerSocket(3345)) {
- Socket client = server.accept();
- System.out.println("Connection accepted.");
- OutputStream out = new FileOutputStream("/../../home/denis/IdeaProjects/ParserHSE/out/production/ParserHSE/sample/gifs/giphy123.gif");
- System.out.println("DataOutputStream created");
- DataInputStream in = new DataInputStream(client.getInputStream());
- System.out.println("DataInputStream created");
- //while(!client.isClosed()) {
- System.out.println("Server reading from channel");
- int count = in.readInt();
- System.out.println(count);
- byte[] bytes = new byte[count];
- if(count > 1){
- //bytes = new byte[count];
- in.read(bytes, 0, count);
- }
- *//*byte[] buffer = new byte[8192];
- while ((count = in.read(buffer)) > 0) {
- out.write(buffer, 0, count);
- System.out.println("qweqweqwe");
- }*//*
- try (FileOutputStream fos = new FileOutputStream("/../../home/denis/IdeaProjects/ParserHSE/out/production/ParserHSE/sample/gifs/giphy123.gif")) {
- fos.write(bytes);
- }
- //out.flush();
- //}
- in.close();
- out.close();
- client.close();
- System.out.println("Closing connections & channels - DONE.");
- } catch (IOException e) {
- e.printStackTrace();
- }*/
- try (ServerSocket server= new ServerSocket(3345);){
- // становимся в ожидание подключения к сокету под именем - "client" на серверной стороне
- Socket client = server.accept();
- // после хэндшейкинга сервер ассоциирует подключающегося клиента с этим сокетом-соединением
- System.out.print("Connection accepted.");
- // инициируем каналы общения в сокете, для сервера
- // канал чтения из сокета
- InputStream in = (client.getInputStream());
- System.out.println("DataInputStream created");
- // канал записи в сокет
- OutputStream out = new FileOutputStream("/../../home/denis/IdeaProjects/ParserHSE/out/production/ParserHSE/sample/gifs/giphy123.gif");
- System.out.println("DataOutputStream created");
- // начинаем диалог с подключенным клиентом в цикле, пока сокет не закрыт
- while(!client.isClosed()){
- System.out.println("Server reading from channel");
- // сервер ждёт в канале чтения (inputstream) получения данных клиента
- byte[] bytes = new byte[558095];
- int count;
- while ((count = in.read(bytes)) > 0) {
- out.write(bytes, 0, count);
- }
- //out.flush();
- //if(count > 1){
- //bytes = new byte[count];
- //System.out.println(in.read(bytes, 0, 558095) + "sdf");
- //}
- //String entry = in.readUTF();
- // после получения данных считывает их
- // System.out.println("READ from client message - "+entry);
- // и выводит в консоль
- System.out.println("Server try writing to channelfftghfthrftgh");
- // инициализация проверки условия продолжения работы с клиентом по этому сокету по кодовому слову
- // если условие окончания работы не верно - продолжаем работу - отправляем эхо обратно клиенту
- //out.writeUTF("Server reply - "+entry + " - OK");
- /*try (FileOutputStream stream = new FileOutputStream("/../../home/denis/IdeaProjects/ParserHSE/out/production/ParserHSE/sample/gifs/giphy123.gif")) {
- stream.write(bytes);
- }*/
- System.out.println("Server Wrote message to client.");
- // освобождаем буфер сетевых сообщений
- //out.flush();
- }
- // если условие выхода - верно выключаем соединения
- System.out.println("Client disconnected");
- System.out.println("Closing connections & channels.");
- // закрываем сначала каналы сокета !
- in.close();
- out.close();
- // потом закрываем сокет общения на стороне сервера!
- client.close();
- // потом закрываем сокет сервера который создаёт сокеты общения
- // хотя при многопоточном применении его закрывать не нужно
- // для возможности поставить этот серверный сокет обратно в ожидание нового подключения
- server.close();
- System.out.println("Closing connections & channels - DONE.");
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement