SHARE
TWEET

Untitled

a guest Jan 24th, 2020 89 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import java.net.*;
  2. import java.io.*;
  3. import java.util.HashMap;
  4. import java.lang.*;
  5. import java.util.*;
  6.  
  7. public class Server {
  8.  
  9.     public static String newLine = "\n";
  10.     public static HashMap<String, int[]> clientsHmap = new HashMap<String, int[]>(); //Stores client info
  11.  
  12.     private int port;
  13.     private Socket socket = null;
  14.     private BufferedReader in = null;
  15.     private ServerSocket serverSocket = null;
  16.     private PrintWriter out = null;
  17.     private boolean listening = true;
  18.  
  19.  
  20.     public Server(int port) {
  21.         this.port = port;
  22.     }
  23.  
  24.     public void run() throws IOException {
  25.         try {
  26.             serverSocket = new ServerSocket(this.port);
  27.         } catch (IOException e) {
  28.             System.err.println("Could not listen on port: " + this.port);
  29.             System.exit(1);
  30.         }
  31.         System.out.println("Listening on port: " + this.port);
  32.  
  33.         while (listening) {
  34.             try {
  35.  
  36.                 socket = serverSocket.accept();
  37.  
  38.                 out = new PrintWriter(socket.getOutputStream(), true); //Response
  39.                 in = new BufferedReader(
  40.                     new InputStreamReader(socket.getInputStream())
  41.                 );
  42.  
  43.                 String line;
  44.                 String request = "";
  45.                 String cookie = ""; // Cookie string
  46.  
  47.  
  48.                 while (in.ready()) {
  49.                     line = in.readLine(); // Read input
  50.                     //System.out.println(line); // Log
  51.                     //out.println(line); // Echo
  52.                     request += line + newLine;  // Structure request
  53.  
  54.                     if (line.contains("Cookie:")==true) {
  55.                       cookie = line.replace("Cookie: JSESSIONID=", ""); // Store cookie
  56.                     }
  57.  
  58.                     if (line.equals("")) {
  59.                       handleRequest(request, cookie, in, out);
  60.                       break;
  61.                     }
  62.                 }
  63.               }catch (IOException e){
  64.                   e.printStackTrace();
  65.               } finally {
  66.                   out.close();
  67.                   in.close();
  68.                   socket.close();
  69.               }
  70.           }
  71.           serverSocket.close();
  72.       }
  73.  
  74.       // Handles incoming http request and generates appropriate response.
  75.       // Generates a cookie for new clients through newGame() function and adds them to the clients Hashmap
  76.       // calls sendResponse() function
  77.       public void handleRequest(String request, String cookie, BufferedReader in, PrintWriter out) {
  78.         int guess = 0;
  79.         String guessStatus = "";
  80.  
  81.         if (request.contains("POST")) {
  82.           char letter;
  83.           StringBuilder postRequest = new StringBuilder();
  84.           try {
  85.             while (in.ready()) {
  86.               letter = (char)in.read();
  87.               postRequest.append(letter);
  88.             }
  89.           } catch (IOException e) {
  90.             e.printStackTrace();
  91.           }
  92.           String guessString = postRequest.toString().replace("guess=", "");  // Extract client's guess
  93.  
  94.           //Check if guess is a number
  95.           try{
  96.             guess = Integer.parseInt(guessString);
  97.           } catch (NumberFormatException e){
  98.             // Invalid guess; not a number
  99.             System.out.println("UNABLE TO CONVERT GUESS TO INT.");
  100.             //sendResponse("invalidInt", cookie, in, out);
  101.           }
  102.         }
  103.  
  104.         // Generate Cookie if new client
  105.         if ((request.contains("GET")) && (request.contains("Cookie:")==false)) {
  106.           System.out.println("NEW CLIENT. GENERATE COOKIE.");
  107.           newGame(in, out);
  108.         } else {         // Update game
  109.           int[] clientInfo = new int[4]; // 0: correct answer, 1: number of guesses, 2: min, 3: max
  110.           clientInfo = clientsHmap.get(cookie); // Gives value for cookie-key
  111.  
  112.           // Reset client cookie if null
  113.           if ((request.contains("GET")) && (clientInfo == null)) {
  114.             System.out.println("CLIENT HAS NULLCOOKIE. GENERATING NEW COOKIE.");
  115.             newGame(in, out);
  116.           }
  117.  
  118.           // If client closes and reopens browser
  119.           else if ((request.contains("GET")) && (request.contains("Cookie:")))  {
  120.             System.out.println("CLIENT CLOSED AND REOPENED BROWSER");
  121.             sendResponse("reopenedBrowser", cookie, in, out);
  122.           }
  123.  
  124.           // Correct guess from client
  125.           else if ((request.contains("POST")) && (guess==clientInfo[0])) {
  126.             sendResponse("end", cookie, in, out);
  127.             clientsHmap.remove(cookie);
  128.           }
  129.  
  130.           // Incorrect guess from client
  131.           else if ((request.contains("POST")) && (guess != clientInfo[0])) {
  132.             if ((guess < 1) || (guess > 100)) { // Check if guess is out of bounds, i.e not in [1,100]
  133.               guessStatus = "outOfBounds";
  134.             } else { // Guess is valid, in range -> accepted
  135.               if (guess < clientInfo[0]) {
  136.                 if (guess >= clientInfo[2]) {
  137.                   clientInfo[2] = guess;  // Update min
  138.                   guessStatus = "minUpdated";
  139.                 } else {
  140.                 guessStatus = "minUpdated";
  141.               }
  142.               }
  143.               if (guess > clientInfo[0]) {
  144.                 if (guess <= clientInfo[3]) {
  145.                   clientInfo[3] = guess;  // Update max
  146.                   guessStatus = "maxUpdated";
  147.                 } else {
  148.                   guessStatus = "maxUpdated";
  149.                 }
  150.               }
  151.               clientInfo[1] += 1; // Increment number of guesses for client
  152.  
  153.             }
  154.             clientsHmap.put(cookie, clientInfo); // Update clients log
  155.             sendResponse(guessStatus, cookie, in, out);
  156.           }
  157.         }
  158.         showActiveClients(); // Run after every request to track clients and gamestates
  159.       }
  160.  
  161.     // Builds a HTML-response based on
  162.     // guessStatus = "start", "end", "outOfBounds", "minUpdated", "maxUpdated"
  163.     // and client's cookie
  164.     public void sendResponse(String guessStatus, String cookie, BufferedReader in, PrintWriter out) {
  165.       String[] htmlResponse = readHtmlFile();
  166.  
  167.       int[] clientInfo = new int[4];
  168.       clientInfo = clientsHmap.get(cookie); // Get client info from clients hash map
  169.  
  170.       out.println("HTTP/1.1 200 OK"); // Initial line
  171.       out.println("Content-Type: text/html"); // Specifies content in message
  172.  
  173.       if (guessStatus.equals("start")) {
  174.         out.println(cookie);
  175.       }
  176.  
  177.       out.println(newLine);
  178.       out.println(htmlResponse[0]);
  179.       out.println(htmlResponse[1]);
  180.       out.println(htmlResponse[2]);
  181.       out.println(htmlResponse[3]);
  182.       out.println(htmlResponse[4]);
  183.       out.println(htmlResponse[5]);
  184.       out.println(htmlResponse[6]);
  185.       out.println(htmlResponse[7]);
  186.  
  187.       String top_text;
  188.       String middle_text;
  189.       String bottom_text;
  190.  
  191.       if (guessStatus.equals("start")) {
  192.         top_text = "Welcome to the Number Guess Game.";
  193.         middle_text = "Guess a number between 1 and 100.";
  194.         bottom_text = "";
  195.         out.println(htmlResponse[8].replace("{top_text}", top_text));
  196.         out.println(htmlResponse[9].replace("{middle_text}", middle_text));
  197.         out.println(htmlResponse[10].replace("{bottom_text}", bottom_text));
  198.       }
  199.       if (guessStatus.equals("invalidInt")) {
  200.         top_text = "Wops!!! You did not enter a number!";
  201.         middle_text = "Guess a number between "+Integer.toString(clientInfo[2])+" and "+Integer.toString(clientInfo[3])+".";
  202.         bottom_text = "You have guessed "+Integer.toString(clientInfo[1])+" times.";
  203.         out.println(htmlResponse[8].replace("{top_text}", top_text));
  204.         out.println(htmlResponse[9].replace("{middle_text}", middle_text));
  205.         out.println(htmlResponse[10].replace("{bottom_text}", bottom_text));
  206.       }
  207.       if (guessStatus.equals("outOfBounds")) {
  208.         top_text = "Wops!!! Guess was out of range!";
  209.         middle_text = "Guess a number between "+Integer.toString(clientInfo[2])+" and "+Integer.toString(clientInfo[3])+".";
  210.         bottom_text = "You have guessed "+Integer.toString(clientInfo[1])+" times.";
  211.         out.println(htmlResponse[8].replace("{top_text}", top_text));
  212.         out.println(htmlResponse[9].replace("{middle_text}", middle_text));
  213.         out.println(htmlResponse[10].replace("{bottom_text}", bottom_text));
  214.       }
  215.       if (guessStatus.equals("minUpdated")) {
  216.         top_text = "Guess was too low!";
  217.         middle_text = "Guess a number between "+clientInfo[2]+" and "+clientInfo[3]+".";
  218.         bottom_text = "You have guessed "+Integer.toString(clientInfo[1])+" times.";
  219.         out.println(htmlResponse[8].replace("{top_text}", top_text));
  220.         out.println(htmlResponse[9].replace("{middle_text}", middle_text));
  221.         out.println(htmlResponse[10].replace("{bottom_text}", bottom_text));
  222.       }
  223.       if (guessStatus.equals("maxUpdated")) {
  224.         top_text = "Guess was too high!";
  225.         middle_text = "Guess a number between "+Integer.toString(clientInfo[2])+" and "+Integer.toString(clientInfo[3])+".";
  226.         bottom_text = "You have guessed "+Integer.toString(clientInfo[1])+" times.";
  227.         out.println(htmlResponse[8].replace("{top_text}", top_text));
  228.         out.println(htmlResponse[9].replace("{middle_text}", middle_text));
  229.         out.println(htmlResponse[10].replace("{bottom_text}", bottom_text));
  230.       }
  231.       if (guessStatus.equals("reopenedBrowser")) {
  232.         top_text = "Welcome back!";
  233.         middle_text = "Guess a number between "+Integer.toString(clientInfo[2])+" and "+Integer.toString(clientInfo[3])+".";
  234.         bottom_text = "You have guessed "+Integer.toString(clientInfo[1])+" times.";
  235.         out.println(htmlResponse[8].replace("{top_text}", top_text));
  236.         out.println(htmlResponse[9].replace("{middle_text}", middle_text));
  237.         out.println(htmlResponse[10].replace("{bottom_text}", bottom_text));
  238.       }
  239.       if (guessStatus.equals("end")) {
  240.         top_text = "You made it! Nice job!";
  241.         middle_text = "It took you "+Integer.toString(clientInfo[1])+" guesses to win.";
  242.         bottom_text = "<P><a href='.'>'New Game'</a></P>";
  243.         out.println(htmlResponse[8].replace("{top_text}", top_text));
  244.         out.println(htmlResponse[9].replace("{middle_text}", middle_text));
  245.         out.println(htmlResponse[10].replace("{bottom_text}", bottom_text));
  246.       } else {
  247.         out.println(htmlResponse[11]);
  248.         out.println(htmlResponse[12]);
  249.         out.println(htmlResponse[13]);
  250.         out.println(htmlResponse[14]);
  251.       }
  252.       out.println(htmlResponse[15]);
  253.       out.println(htmlResponse[16]);
  254.     }
  255.  
  256.     public static String[] readHtmlFile() {
  257.       String[] html = new String[17];
  258.       String guessFile = "guess.html";
  259.       String line;
  260.       try {
  261.         FileReader fr = new FileReader(guessFile);
  262.         BufferedReader br = new BufferedReader(fr);
  263.  
  264.         int row = 0;
  265.         while ((line = br.readLine()) != null) {
  266.           html[row] = line;
  267.           row += 1;
  268.         }
  269.         br.close();
  270.       } catch (FileNotFoundException e) {
  271.         // Could not find file
  272.         System.out.println("Could not find file: '"+guessFile+"'.");
  273.       } catch (IOException e) {
  274.         // Could not read file
  275.         e.printStackTrace();
  276.       }
  277.  
  278.       return html;
  279.     }
  280.  
  281.     // Generates new cookie for client
  282.     public void newGame(BufferedReader in, PrintWriter out) {
  283.       int[] clientInfo = new int[4];  // 0: correct answer, 1: number of guesses, 2: min, 3: max
  284.  
  285.       long currentTimeLong = System.currentTimeMillis(); // Using current time (milliseconds) as cookie
  286.       String currentTime = Long.toString(currentTimeLong);
  287.       String cookie = "Set-Cookie: JSESSIONID="+currentTime;
  288.       int correctAnswer = (int)(Math.random() * 100 + 1); // Generating correct answer
  289.  
  290.       clientInfo[0] = correctAnswer;
  291.       clientInfo[1] = 0;
  292.       clientInfo[2] = 1;
  293.       clientInfo[3] = 100;
  294.  
  295.       clientsHmap.put(currentTime, clientInfo);
  296.       sendResponse("start", cookie, in, out);
  297.     }
  298.  
  299.     // Displays all active clients and their info
  300.     public void showActiveClients() {
  301.       //System.out.println("-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/");
  302.       int[] clientInfo = new int[4];
  303.       Set<String> keys = clientsHmap.keySet();
  304.       for(String key: keys) {
  305.         System.out.println("Client: " + key);
  306.         clientInfo = clientsHmap.get(key);
  307.         for (int i=0; i<4; i++) {
  308.           System.out.println(clientInfo[i]);
  309.         }
  310.       }
  311.       System.out.println("-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/");
  312.     }
  313.  
  314.     public static void main(String[] args) throws IOException {
  315.         Server s = new Server(8989);
  316.         s.run();
  317.     }
  318. }
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
Top