paranid5

socket

Jul 27th, 2021 (edited)
555
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Client.java
  2.  
  3. import java.io.*;
  4. import java.net.Socket;
  5.  
  6. public final class Client {
  7.     public static final void main(final String[] args) throws IOException {
  8.         final var out = System.out;
  9.  
  10.         try (
  11.                 final var stdin = new BufferedReader(new InputStreamReader(System.in));
  12.                 final var socket = new Socket("127.0.0.1", 1337);
  13.                 final var socketReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
  14.                 final var socketWriter = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true)
  15.         ) {
  16.             out.println("String: ");
  17.  
  18.             final var s = stdin.readLine();
  19.             socketWriter.println(s.length());
  20.             socketWriter.println(s);
  21.  
  22.             final var size = Integer.parseInt(socketReader.readLine());
  23.             final var builder = new StringBuilder();
  24.  
  25.             do { builder.append(socketReader.readLine()); }
  26.             while (builder.length() < size);
  27.  
  28.             out.println(builder);
  29.         }
  30.     }
  31. }
  32. // Server.java
  33.  
  34. import java.io.*;
  35. import java.net.InetAddress;
  36. import java.net.ServerSocket;
  37. import java.util.concurrent.Executors;
  38.  
  39. public final class Server {
  40.     public static final void main(final String[] args) throws IOException {
  41.         final var executor = Executors.newCachedThreadPool();
  42.         final var server = new ServerSocket(1337, 50, InetAddress.getByName("127.0.0.1"));
  43.  
  44.         while (true) {
  45.             final var client = server.accept();
  46.             final var reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
  47.             final var writer = new PrintWriter(new OutputStreamWriter(client.getOutputStream()), true);
  48.  
  49.             final var builder = new StringBuilder();
  50.  
  51.             executor.execute(() -> {
  52.                 try {
  53.                     final var size = Integer.parseInt(reader.readLine());
  54.  
  55.                     do { builder.append(reader.readLine()); }
  56.                     while (builder.length() < size);
  57.  
  58.                     writer.println(builder.length());
  59.                     writer.println(builder.reverse());
  60.                     client.close();reader.close();writer.close();
  61.                 } catch (final Exception ignored) {}
  62.             });
  63.         }
  64.  
  65.         // server.close(); Unreachable statement
  66.     }
  67. }
  68.  
  69.  
RAW Paste Data