Advertisement
Guest User

ServerSimulator2017

a guest
Nov 30th, 2017
228
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.99 KB | None | 0 0
  1. import java.io.IOException;
  2. import java.net.ServerSocket;
  3. import java.net.Socket;
  4. import java.util.concurrent.atomic.AtomicInteger;
  5.  
  6. public class ServerSimulator2017 {
  7.  
  8.     private static final boolean SIMULATE_PROCESSING = false;
  9.     private static final int PORT = 443;
  10.     private static final AtomicInteger LAST_SECOND_REQUESTS = new AtomicInteger(0);
  11.     private static final AtomicInteger ALL_REQUESTS = new AtomicInteger(0);
  12.  
  13.  
  14.     public static void main(String[] args) throws IOException {
  15.         final long start = System.currentTimeMillis();
  16.         final ServerSocket ss = new ServerSocket(PORT);
  17.  
  18.         new Thread(() -> {
  19.             while (true) {
  20.                 System.out.println("Requests in the last second: " + LAST_SECOND_REQUESTS.getAndSet(0));
  21.                 System.out.println("Avg: " + (ALL_REQUESTS.get() * 1000 / (float) (System.currentTimeMillis() - start)) + " req/sec");
  22.                 System.out.println("------------------------------------");
  23.                 try {
  24.                     Thread.sleep(1000);
  25.                 } catch (InterruptedException e) {
  26.                     e.printStackTrace();
  27.                 }
  28.             }
  29.         }).start();
  30.  
  31.         while (true) {
  32.             new RequestHandler(ss.accept()).start();
  33.             LAST_SECOND_REQUESTS.getAndIncrement();
  34.             ALL_REQUESTS.getAndIncrement();
  35.         }
  36.     }
  37.  
  38.     private static class RequestHandler extends Thread {
  39.  
  40.         private final Socket client;
  41.  
  42.         private RequestHandler(Socket client) {
  43.             this.client = client;
  44.         }
  45.  
  46.         @Override
  47.         public void run() {
  48.             if (SIMULATE_PROCESSING) {
  49.                 try {
  50.                     Thread.sleep(1000);
  51.                 } catch (InterruptedException e) {
  52.                     throw new IllegalStateException(e);
  53.                 }
  54.             }
  55.             try {
  56.                 client.close();
  57.             } catch (IOException ignored) {
  58.             }
  59.         }
  60.     }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement