Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.net.*;
- import java.io.*;
- import java.util.HashMap;
- import java.lang.*;
- import java.util.*;
- public class Server {
- public static String newLine = "\n";
- public static HashMap<String, int[]> clientsHmap = new HashMap<String, int[]>(); //Stores client info
- private int port;
- private Socket socket = null;
- private BufferedReader in = null;
- private ServerSocket serverSocket = null;
- private PrintWriter out = null;
- private boolean listening = true;
- public Server(int port) {
- this.port = port;
- }
- public void run() throws IOException {
- try {
- serverSocket = new ServerSocket(this.port);
- } catch (IOException e) {
- System.err.println("Could not listen on port: " + this.port);
- System.exit(1);
- }
- System.out.println("Listening on port: " + this.port);
- while (listening) {
- try {
- socket = serverSocket.accept();
- out = new PrintWriter(socket.getOutputStream(), true); //Response
- in = new BufferedReader(
- new InputStreamReader(socket.getInputStream())
- );
- String line;
- String request = "";
- String cookie = ""; // Cookie string
- while (in.ready()) {
- line = in.readLine(); // Read input
- //System.out.println(line); // Log
- //out.println(line); // Echo
- request += line + newLine; // Structure request
- if (line.contains("Cookie:")==true) {
- cookie = line.replace("Cookie: JSESSIONID=", ""); // Store cookie
- }
- if (line.equals("")) {
- handleRequest(request, cookie, in, out);
- break;
- }
- }
- }catch (IOException e){
- e.printStackTrace();
- } finally {
- out.close();
- in.close();
- socket.close();
- }
- }
- serverSocket.close();
- }
- // Handles incoming http request and generates appropriate response.
- // Generates a cookie for new clients through newGame() function and adds them to the clients Hashmap
- // calls sendResponse() function
- public void handleRequest(String request, String cookie, BufferedReader in, PrintWriter out) {
- int guess = 0;
- String guessStatus = "";
- if (request.contains("POST")) {
- char letter;
- StringBuilder postRequest = new StringBuilder();
- try {
- while (in.ready()) {
- letter = (char)in.read();
- postRequest.append(letter);
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- String guessString = postRequest.toString().replace("guess=", ""); // Extract client's guess
- //Check if guess is a number
- try{
- guess = Integer.parseInt(guessString);
- } catch (NumberFormatException e){
- // Invalid guess; not a number
- System.out.println("UNABLE TO CONVERT GUESS TO INT.");
- //sendResponse("invalidInt", cookie, in, out);
- }
- }
- // Generate Cookie if new client
- if ((request.contains("GET")) && (request.contains("Cookie:")==false)) {
- System.out.println("NEW CLIENT. GENERATE COOKIE.");
- newGame(in, out);
- } else { // Update game
- int[] clientInfo = new int[4]; // 0: correct answer, 1: number of guesses, 2: min, 3: max
- clientInfo = clientsHmap.get(cookie); // Gives value for cookie-key
- // Reset client cookie if null
- if ((request.contains("GET")) && (clientInfo == null)) {
- System.out.println("CLIENT HAS NULLCOOKIE. GENERATING NEW COOKIE.");
- newGame(in, out);
- }
- // If client closes and reopens browser
- else if ((request.contains("GET")) && (request.contains("Cookie:"))) {
- System.out.println("CLIENT CLOSED AND REOPENED BROWSER");
- sendResponse("reopenedBrowser", cookie, in, out);
- }
- // Correct guess from client
- else if ((request.contains("POST")) && (guess==clientInfo[0])) {
- sendResponse("end", cookie, in, out);
- clientsHmap.remove(cookie);
- }
- // Incorrect guess from client
- else if ((request.contains("POST")) && (guess != clientInfo[0])) {
- if ((guess < 1) || (guess > 100)) { // Check if guess is out of bounds, i.e not in [1,100]
- guessStatus = "outOfBounds";
- } else { // Guess is valid, in range -> accepted
- if (guess < clientInfo[0]) {
- if (guess >= clientInfo[2]) {
- clientInfo[2] = guess; // Update min
- guessStatus = "minUpdated";
- } else {
- guessStatus = "minUpdated";
- }
- }
- if (guess > clientInfo[0]) {
- if (guess <= clientInfo[3]) {
- clientInfo[3] = guess; // Update max
- guessStatus = "maxUpdated";
- } else {
- guessStatus = "maxUpdated";
- }
- }
- clientInfo[1] += 1; // Increment number of guesses for client
- }
- clientsHmap.put(cookie, clientInfo); // Update clients log
- sendResponse(guessStatus, cookie, in, out);
- }
- }
- showActiveClients(); // Run after every request to track clients and gamestates
- }
- // Builds a HTML-response based on
- // guessStatus = "start", "end", "outOfBounds", "minUpdated", "maxUpdated"
- // and client's cookie
- public void sendResponse(String guessStatus, String cookie, BufferedReader in, PrintWriter out) {
- String[] htmlResponse = readHtmlFile();
- int[] clientInfo = new int[4];
- clientInfo = clientsHmap.get(cookie); // Get client info from clients hash map
- out.println("HTTP/1.1 200 OK"); // Initial line
- out.println("Content-Type: text/html"); // Specifies content in message
- if (guessStatus.equals("start")) {
- out.println(cookie);
- }
- out.println(newLine);
- out.println(htmlResponse[0]);
- out.println(htmlResponse[1]);
- out.println(htmlResponse[2]);
- out.println(htmlResponse[3]);
- out.println(htmlResponse[4]);
- out.println(htmlResponse[5]);
- out.println(htmlResponse[6]);
- out.println(htmlResponse[7]);
- String top_text;
- String middle_text;
- String bottom_text;
- if (guessStatus.equals("start")) {
- top_text = "Welcome to the Number Guess Game.";
- middle_text = "Guess a number between 1 and 100.";
- bottom_text = "";
- out.println(htmlResponse[8].replace("{top_text}", top_text));
- out.println(htmlResponse[9].replace("{middle_text}", middle_text));
- out.println(htmlResponse[10].replace("{bottom_text}", bottom_text));
- }
- if (guessStatus.equals("invalidInt")) {
- top_text = "Wops!!! You did not enter a number!";
- middle_text = "Guess a number between "+Integer.toString(clientInfo[2])+" and "+Integer.toString(clientInfo[3])+".";
- bottom_text = "You have guessed "+Integer.toString(clientInfo[1])+" times.";
- out.println(htmlResponse[8].replace("{top_text}", top_text));
- out.println(htmlResponse[9].replace("{middle_text}", middle_text));
- out.println(htmlResponse[10].replace("{bottom_text}", bottom_text));
- }
- if (guessStatus.equals("outOfBounds")) {
- top_text = "Wops!!! Guess was out of range!";
- middle_text = "Guess a number between "+Integer.toString(clientInfo[2])+" and "+Integer.toString(clientInfo[3])+".";
- bottom_text = "You have guessed "+Integer.toString(clientInfo[1])+" times.";
- out.println(htmlResponse[8].replace("{top_text}", top_text));
- out.println(htmlResponse[9].replace("{middle_text}", middle_text));
- out.println(htmlResponse[10].replace("{bottom_text}", bottom_text));
- }
- if (guessStatus.equals("minUpdated")) {
- top_text = "Guess was too low!";
- middle_text = "Guess a number between "+clientInfo[2]+" and "+clientInfo[3]+".";
- bottom_text = "You have guessed "+Integer.toString(clientInfo[1])+" times.";
- out.println(htmlResponse[8].replace("{top_text}", top_text));
- out.println(htmlResponse[9].replace("{middle_text}", middle_text));
- out.println(htmlResponse[10].replace("{bottom_text}", bottom_text));
- }
- if (guessStatus.equals("maxUpdated")) {
- top_text = "Guess was too high!";
- middle_text = "Guess a number between "+Integer.toString(clientInfo[2])+" and "+Integer.toString(clientInfo[3])+".";
- bottom_text = "You have guessed "+Integer.toString(clientInfo[1])+" times.";
- out.println(htmlResponse[8].replace("{top_text}", top_text));
- out.println(htmlResponse[9].replace("{middle_text}", middle_text));
- out.println(htmlResponse[10].replace("{bottom_text}", bottom_text));
- }
- if (guessStatus.equals("reopenedBrowser")) {
- top_text = "Welcome back!";
- middle_text = "Guess a number between "+Integer.toString(clientInfo[2])+" and "+Integer.toString(clientInfo[3])+".";
- bottom_text = "You have guessed "+Integer.toString(clientInfo[1])+" times.";
- out.println(htmlResponse[8].replace("{top_text}", top_text));
- out.println(htmlResponse[9].replace("{middle_text}", middle_text));
- out.println(htmlResponse[10].replace("{bottom_text}", bottom_text));
- }
- if (guessStatus.equals("end")) {
- top_text = "You made it! Nice job!";
- middle_text = "It took you "+Integer.toString(clientInfo[1])+" guesses to win.";
- bottom_text = "<P><a href='.'>'New Game'</a></P>";
- out.println(htmlResponse[8].replace("{top_text}", top_text));
- out.println(htmlResponse[9].replace("{middle_text}", middle_text));
- out.println(htmlResponse[10].replace("{bottom_text}", bottom_text));
- } else {
- out.println(htmlResponse[11]);
- out.println(htmlResponse[12]);
- out.println(htmlResponse[13]);
- out.println(htmlResponse[14]);
- }
- out.println(htmlResponse[15]);
- out.println(htmlResponse[16]);
- }
- public static String[] readHtmlFile() {
- String[] html = new String[17];
- String guessFile = "guess.html";
- String line;
- try {
- FileReader fr = new FileReader(guessFile);
- BufferedReader br = new BufferedReader(fr);
- int row = 0;
- while ((line = br.readLine()) != null) {
- html[row] = line;
- row += 1;
- }
- br.close();
- } catch (FileNotFoundException e) {
- // Could not find file
- System.out.println("Could not find file: '"+guessFile+"'.");
- } catch (IOException e) {
- // Could not read file
- e.printStackTrace();
- }
- return html;
- }
- // Generates new cookie for client
- public void newGame(BufferedReader in, PrintWriter out) {
- int[] clientInfo = new int[4]; // 0: correct answer, 1: number of guesses, 2: min, 3: max
- long currentTimeLong = System.currentTimeMillis(); // Using current time (milliseconds) as cookie
- String currentTime = Long.toString(currentTimeLong);
- String cookie = "Set-Cookie: JSESSIONID="+currentTime;
- int correctAnswer = (int)(Math.random() * 100 + 1); // Generating correct answer
- clientInfo[0] = correctAnswer;
- clientInfo[1] = 0;
- clientInfo[2] = 1;
- clientInfo[3] = 100;
- clientsHmap.put(currentTime, clientInfo);
- sendResponse("start", cookie, in, out);
- }
- // Displays all active clients and their info
- public void showActiveClients() {
- //System.out.println("-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/");
- int[] clientInfo = new int[4];
- Set<String> keys = clientsHmap.keySet();
- for(String key: keys) {
- System.out.println("Client: " + key);
- clientInfo = clientsHmap.get(key);
- for (int i=0; i<4; i++) {
- System.out.println(clientInfo[i]);
- }
- }
- System.out.println("-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/");
- }
- public static void main(String[] args) throws IOException {
- Server s = new Server(8989);
- s.run();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement