Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.net.*;
- import java.lang.*;
- import java.util.*;
- import java.util.HashMap;
- public class karlServer {
- private final int port = 8989;
- private ServerSocket serverSocket = null;
- public static HashMap<String, int[]> sessionMap = new HashMap<String, int[]>();
- public static String clue = "Guess a number between 1 and 100";
- public static String history = "You have guessed 0 times";
- public static void main(String[] args) {
- new karlServer();
- }
- public karlServer() {
- try (ServerSocket serverSocket = new ServerSocket(this.port)) {
- System.out.println("Listening on port: " + this.port);
- String requestType = "";
- StringBuilder postRequest = new StringBuilder();
- int guess = 999999;
- String cookie="0";
- Boolean startGame = false;
- while (true) { // While listening
- try (Socket socket = serverSocket.accept();
- BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
- PrintWriter printWriteOut = new PrintWriter(socket.getOutputStream(), true)) {
- System.err.println("Connected on " + this.port);
- String line;
- String tempLine = "Not yet initialized";
- String[] htmlResponse = readHtmlFile("guess.html"); // Read html-file that we will update based on what client send.
- while ((line = in.readLine()) != null) { // read
- tempLine = line;
- System.out.println(" <<< " + line); // log
- if (line.matches("GET\\s+.*")) {
- // process the GET request
- System.err.println("Vi har en GET request");
- requestType = "GET";
- cookie = GETreader(in, printWriteOut, cookie);
- }
- if (line.matches("POST\\s+.*")) {
- // process the POST request
- System.err.println("Vi har en POST request");
- requestType = "POST";
- String[] postResult = POSTreader(in, printWriteOut, cookie); // Kanske kan ta bort cookie här
- cookie = postResult[1];
- String guessString = postResult[0];
- // Convert the guess to an integer
- try{
- guess = Integer.parseInt(guessString);
- } catch (NumberFormatException e){
- System.out.println("The guess was not a number.");
- }
- }
- break;
- }
- // The Game
- System.err.println("Check if first letter in cookie = S");
- System.err.println("Cookie: " + cookie);
- if (cookie.charAt(0) == 'S') {
- startGame = true;
- clue = "Guess a number between 1 and 100";
- history = "You have guessed 0 times";
- System.err.println("First letter did equal S and we set startGame = true;");
- } else {
- startGame = false;
- }
- if (startGame != true) {
- System.err.println("Eftersom det inte var startGame så hämtar vi info på denna cookie: " + cookie);
- int[] client = sessionMap.get(cookie); // [0] = Correct Answer
- // [1] = Number of Guesses
- // [2] = Min Guess
- // [3] = Max Guess
- System.err.println("Vi försöker plocka ut info med denna cookie: " + cookie);
- history = "You have guessed " + String.valueOf(client[1]) + " times";
- if (guess != client[0]){
- if (guess< 1 || guess > 100) {
- requestType = "Your guess was out of bounds, you have to guess a number higher than 1 and lower than 100";
- history = requestType;
- }
- if (guess< client[2] || guess > client[3]) {
- requestType = "The guess was smaller current min or larger than current max";
- // No update needed
- }
- if (requestType == "POST") {
- if (guess > client[0] && guess != 999999){ // Less than current max guess
- client[3] = guess;
- }
- if (guess < client[0]){
- client[2] = guess;
- }
- }
- clue = "Guess a number between " + String.valueOf(client[2]) + " and " + String.valueOf(client[3]);
- sessionMap.replace(cookie, client); // Kanske även ska store counter
- } else {
- // You won!
- // Fixa svaren för det
- clue = "Happy boy! You have guessed have guessed the correct number: " + String.valueOf(client[0]);
- history = "It only took you " + String.valueOf(client[1]) + " guesses!";
- sessionMap.remove(cookie);
- }
- // For me to see where it's at
- System.err.println("------------------------------");
- System.err.println("We had a guess and updated the Session");
- System.err.println("Correct answer gameInfo[0] = " + String.valueOf(client[0]));
- System.err.println("Min Guess = " + String.valueOf(client[2]));
- System.err.println("Max Guess = " + String.valueOf(client[3]));
- System.err.println("Stored on the Cookie: = " + cookie);
- System.err.println("------------------------------");
- }
- System.out.println(" >>> " + "HTTP RESPONSE"); // log
- // update html
- htmlResponse[7] = htmlResponse[7].replace("{clue}", clue);
- htmlResponse[9] = htmlResponse[9].replace("{history}", history);
- // Sending response to client
- printWriteOut.println("HTTP/1.1 200 OK"); // Initial line
- printWriteOut.println("Content-Type: text/html"); // Specifies content in message
- System.err.println(" >>> " + "HTTP/1.1 200 OK");
- System.err.println(" >>> " + "Content-Type: text/html");
- if (startGame) {
- printWriteOut.println(cookie);
- }
- printWriteOut.println("\n"); // new line
- for (int row=0; row<htmlResponse.length; row++) {
- System.err.println(" >>> " + htmlResponse[row]);
- printWriteOut.println(htmlResponse[row]);
- }
- // Reset Variables for next request and response
- startGame = false;
- cookie = cookie.replace("Set-Cookie: JSESSIONID=", "");
- // Close this request
- printWriteOut.close();
- System.err.println("We just closed");
- } catch (IOException e) {
- System.err.println(e.getMessage());
- }
- }
- } catch (IOException e) {
- System.err.println(e.getMessage());
- System.err.println("Could not listen on port: " + this.port);
- System.exit(1);
- }
- }
- public String GETreader(BufferedReader in, PrintWriter out, String cookie) {
- Boolean startGame = true;
- String line;
- try {
- while(in.ready()) {
- line = in.readLine();
- System.out.println("In function <<< " + line);
- if(line.contains("Cookie:")==true){
- System.out.println("We had the line " + line);
- cookie = line.substring(line.length()-13, line.length()); // Retrieve the part of cookie line we use as key
- System.out.println("We got this Cookie in the GET request: " + cookie);
- startGame = false;
- }
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- System.err.println("Check if not in sessionMap, key: " + cookie);
- // if (cookie in HashMap) don't start a new game:
- if (!sessionMap.containsKey(cookie)){ startGame = true; System.err.println(cookie + " was not in sessionMap");}
- // else: new game
- if (startGame == true) {
- System.err.println("We have a GET request and should start new game");
- int correct = (int)(Math.random() * 100 + 1); // Correct Answer
- int[] gameInfo = { correct, 0, 1, 100};
- String timeStamp = Long.toString(System.currentTimeMillis());
- cookie = "Set-Cookie: JSESSIONID="+timeStamp;
- sessionMap.put(timeStamp, gameInfo); //cookie = timeStamp;
- System.err.println("------------------------------");
- System.err.println("We started a new game with the following information:");
- System.err.println("Correct answer gameInfo[0] = " + String.valueOf(gameInfo[0]));
- System.err.println("Min Guess = " + String.valueOf(gameInfo[2]));
- System.err.println("Max Guess = " + String.valueOf(gameInfo[3]));
- System.err.println("Stored on the Cookie: = " + cookie);
- System.err.println("------------------------------");
- System.err.println("Put in sessionMap on key: " + timeStamp);
- }
- // Return the cookie that identifies the client who sent the GET request
- // So we can send the apropriate respnse for exactly this client
- return cookie;
- }
- public String[] POSTreader(BufferedReader in, PrintWriter out, String cookie) {
- String line = "";
- int guess = 0;
- try {
- while(in.ready()) {
- line = in.readLine();
- System.out.println("In function <<< " + line);
- if(line.contains("Cookie:")==true) {
- cookie = line.substring(line.length()-13, line.length());
- }
- if(line.equals("")){
- break;
- }
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- int[] client = sessionMap.get(cookie); // [0] = Correct Answer
- // [1] = Number of Guesses
- // [2] = Min Guess
- // [3] = Max Guess
- client[1] += 1; // Add 1 number of guesses for each POST request
- sessionMap.replace(cookie, client); // Update number of guesses in hashMap
- StringBuilder postRequest = new StringBuilder();
- try {
- // For some reason my loop gets stuck if at the empty line everytime,
- // so I have to continue letter by letter from there
- while (in.ready()) {
- char letter = (char)in.read();
- System.out.println("In function <<< " + letter);
- postRequest.append(letter);
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- String guessString = postRequest.toString().replace("guess=", ""); // Remove all but the number
- System.out.println("\n");
- System.err.println("Vår gissning är: " + guessString);
- // Return the guess and the cookie that identifies the client who sent it
- String[] stringArray = new String[]{ guessString, cookie };
- return stringArray;
- }
- public static String[] readHtmlFile(String path) {
- // Read the html file that we use as base for all our responses
- String[] html = new String[16];
- String line;
- try {
- FileReader fr = new FileReader(path);
- BufferedReader br = new BufferedReader(fr);
- int row = 0;
- while ((line = br.readLine()) != null){
- html[row] = line;
- row += 1;
- }
- br.close();
- } catch (FileNotFoundException e) {
- System.out.println("Kan inte hitta file: " + path);
- } catch (IOException e) {
- // Kan inte läsa file
- e.printStackTrace();
- }
- return html;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement