SHARE
TWEET

Untitled

a guest May 20th, 2019 55 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package ru.ifmo.rain.dulaev.hello;
  2.  
  3. import info.kgeorgiy.java.advanced.hello.HelloServer;
  4.  
  5. import java.io.*;
  6. import java.net.DatagramPacket;
  7. import java.net.DatagramSocket;
  8. import java.net.SocketException;
  9. import java.util.Arrays;
  10. import java.util.Objects;
  11. import java.util.concurrent.ExecutorService;
  12. import java.util.concurrent.Executors;
  13. import java.util.concurrent.TimeUnit;
  14.  
  15. public class HelloUDPServer implements HelloServer {
  16.  
  17.     private static final String USAGE = "Usage: HelloUDPServer port threads";
  18.     private static final int TERMINATION_AWAIT_SECONDS = 1;
  19.     private static final boolean VERBOSE = false;
  20.  
  21.     private DatagramSocket socket;
  22.     private ExecutorService mainExecutor;
  23.     private ExecutorService workers;
  24.  
  25.     private int receiveBufferSize = 0;
  26.  
  27.     public static void main(String[] args) {
  28.         if (args == null || args.length != 2) {
  29.             System.out.println(USAGE);
  30.         } else {
  31.             if (Arrays.stream(args).anyMatch(Objects::isNull)) {
  32.                 System.out.println("Non-null arguments expected");
  33.                 return;
  34.             }
  35.             try {
  36.                 int port = Integer.parseInt(args[0]);
  37.                 int threads = Integer.parseInt(args[1]);
  38.  
  39.                 try (HelloServer server = new HelloUDPServer()) {
  40.                     server.start(port, threads);
  41.                     BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
  42.                     reader.readLine();
  43.                 } catch (IOException e) {
  44.                     System.err.println("Could not listen to input command");
  45.                 }
  46.             } catch (NumberFormatException e) {
  47.                 System.out.println("Arguments 'port' ans 'threads' are expected to be integers: " +
  48.                         e.getMessage());
  49.             }
  50.         }
  51.     }
  52.  
  53.     @Override
  54.     public void start(int port, int threads) {
  55.         try {
  56.             socket = new DatagramSocket(port);
  57.             receiveBufferSize = socket.getReceiveBufferSize();
  58.  
  59.             workers = Executors.newFixedThreadPool(threads);
  60.             mainExecutor = Executors.newSingleThreadExecutor();
  61.             mainExecutor.submit(this::receiveAndRespond);
  62.         } catch (SocketException e) {
  63.             System.err.println("Unable to establish connection via socket: " + e.getMessage());
  64.         }
  65.     }
  66.  
  67.     private void receiveAndRespond() {
  68.         try {
  69.             while (!socket.isClosed() && !Thread.interrupted()) {
  70.                 final DatagramPacket request = PacketUtils.newEmptyPacket(receiveBufferSize);
  71.                 socket.receive(request);
  72.  
  73.                 workers.submit(() -> {
  74.                     final String requestMessage = PacketUtils.decodeMessage(request);
  75.                     log(String.format("Received '%s'", requestMessage));
  76.  
  77.                     String responseMessage = "Hello, " + requestMessage;
  78.                     PacketUtils.fillMessage(request, responseMessage);
  79.                     log(String.format("Sending '%s'", responseMessage));
  80.                     try {
  81.                         socket.send(request);
  82.                     } catch (IOException e) {
  83.                         if (!socket.isClosed()) {
  84.                             System.err.println("Error occured while trying to send a response: " + e.getMessage());
  85.                         }
  86.                     }
  87.                 });
  88.             }
  89.         } catch (IOException e) {
  90.             if (!socket.isClosed()) {
  91.                 System.err.println("Error occured while trying to receive a request: " + e.getMessage());
  92.             }
  93.         }
  94.     }
  95.  
  96.     @Override
  97.     public void close() {
  98.         socket.close();
  99.         mainExecutor.shutdown();
  100.         workers.shutdown();
  101.         try {
  102.             mainExecutor.awaitTermination(TERMINATION_AWAIT_SECONDS, TimeUnit.SECONDS);
  103.             workers.awaitTermination(TERMINATION_AWAIT_SECONDS, TimeUnit.SECONDS);
  104.         } catch (InterruptedException e) {
  105.             System.err.println("Could not terminate executor pools: " + e.getMessage());
  106.         }
  107.     }
  108.  
  109.     private static void log(String message) {
  110.         if (VERBOSE) {
  111. //            new PrintStream(System.out, true, StandardCharsets.UTF_8).println(message);
  112.             System.out.println(message);
  113.         }
  114.     }
  115.  
  116. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top