Advertisement
Guest User

Untitled

a guest
Jan 24th, 2020
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.73 KB | None | 0 0
  1. import java.io.*;
  2. import java.net.*;
  3. import java.lang.*;
  4. import java.util.*;
  5. import java.util.HashMap;
  6.  
  7. public class karlServer {
  8. private final int port = 8989;
  9. private ServerSocket serverSocket = null;
  10. public static HashMap<String, int[]> sessionMap = new HashMap<String, int[]>();
  11. public static String clue = "Guess a number between 1 and 100";
  12. public static String history = "You have guessed 0 times";
  13.  
  14.  
  15. public static void main(String[] args) {
  16. new karlServer();
  17. }
  18.  
  19. public karlServer() {
  20. try (ServerSocket serverSocket = new ServerSocket(this.port)) {
  21. System.out.println("Listening on port: " + this.port);
  22.  
  23. String requestType = "";
  24. StringBuilder postRequest = new StringBuilder();
  25. int guess = 999999;
  26. String cookie="0";
  27. Boolean startGame = false;
  28.  
  29. while (true) { // While listening
  30.  
  31. try (Socket socket = serverSocket.accept();
  32. BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
  33. PrintWriter printWriteOut = new PrintWriter(socket.getOutputStream(), true)) {
  34.  
  35. System.err.println("Connected on " + this.port);
  36.  
  37.  
  38. String line;
  39. String tempLine = "Not yet initialized";
  40. String[] htmlResponse = readHtmlFile("guess.html"); // Read html-file that we will update based on what client send.
  41.  
  42. while ((line = in.readLine()) != null) { // read
  43. tempLine = line;
  44. System.out.println(" <<< " + line); // log
  45.  
  46.  
  47. if (line.matches("GET\\s+.*")) {
  48. // process the GET request
  49. System.err.println("Vi har en GET request");
  50. requestType = "GET";
  51.  
  52. cookie = GETreader(in, printWriteOut, cookie);
  53. }
  54.  
  55. if (line.matches("POST\\s+.*")) {
  56. // process the POST request
  57. System.err.println("Vi har en POST request");
  58. requestType = "POST";
  59.  
  60. String[] postResult = POSTreader(in, printWriteOut, cookie); // Kanske kan ta bort cookie här
  61. cookie = postResult[1];
  62. String guessString = postResult[0];
  63. // Convert the guess to an integer
  64. try{
  65. guess = Integer.parseInt(guessString);
  66. } catch (NumberFormatException e){
  67. System.out.println("The guess was not a number.");
  68. }
  69.  
  70. }
  71. break;
  72. }
  73.  
  74. // The Game
  75. System.err.println("Check if first letter in cookie = S");
  76. System.err.println("Cookie: " + cookie);
  77. if (cookie.charAt(0) == 'S') {
  78. startGame = true;
  79. clue = "Guess a number between 1 and 100";
  80. history = "You have guessed 0 times";
  81. System.err.println("First letter did equal S and we set startGame = true;");
  82. } else {
  83. startGame = false;
  84. }
  85.  
  86. if (startGame != true) {
  87. System.err.println("Eftersom det inte var startGame så hämtar vi info på denna cookie: " + cookie);
  88. int[] client = sessionMap.get(cookie); // [0] = Correct Answer
  89. // [1] = Number of Guesses
  90. // [2] = Min Guess
  91. // [3] = Max Guess
  92. System.err.println("Vi försöker plocka ut info med denna cookie: " + cookie);
  93.  
  94. history = "You have guessed " + String.valueOf(client[1]) + " times";
  95. if (guess != client[0]){
  96. if (guess< 1 || guess > 100) {
  97. requestType = "Your guess was out of bounds, you have to guess a number higher than 1 and lower than 100";
  98. history = requestType;
  99. }
  100. if (guess< client[2] || guess > client[3]) {
  101. requestType = "The guess was smaller current min or larger than current max";
  102. // No update needed
  103. }
  104. if (requestType == "POST") {
  105. if (guess > client[0] && guess != 999999){ // Less than current max guess
  106. client[3] = guess;
  107. }
  108. if (guess < client[0]){
  109. client[2] = guess;
  110. }
  111. }
  112. clue = "Guess a number between " + String.valueOf(client[2]) + " and " + String.valueOf(client[3]);
  113. sessionMap.replace(cookie, client); // Kanske även ska store counter
  114. } else {
  115. // You won!
  116. // Fixa svaren för det
  117. clue = "Happy boy! You have guessed have guessed the correct number: " + String.valueOf(client[0]);
  118. history = "It only took you " + String.valueOf(client[1]) + " guesses!";
  119. sessionMap.remove(cookie);
  120. }
  121. // For me to see where it's at
  122. System.err.println("------------------------------");
  123. System.err.println("We had a guess and updated the Session");
  124. System.err.println("Correct answer gameInfo[0] = " + String.valueOf(client[0]));
  125. System.err.println("Min Guess = " + String.valueOf(client[2]));
  126. System.err.println("Max Guess = " + String.valueOf(client[3]));
  127. System.err.println("Stored on the Cookie: = " + cookie);
  128. System.err.println("------------------------------");
  129. }
  130.  
  131. System.out.println(" >>> " + "HTTP RESPONSE"); // log
  132.  
  133. // update html
  134. htmlResponse[7] = htmlResponse[7].replace("{clue}", clue);
  135. htmlResponse[9] = htmlResponse[9].replace("{history}", history);
  136.  
  137. // Sending response to client
  138. printWriteOut.println("HTTP/1.1 200 OK"); // Initial line
  139. printWriteOut.println("Content-Type: text/html"); // Specifies content in message
  140. System.err.println(" >>> " + "HTTP/1.1 200 OK");
  141. System.err.println(" >>> " + "Content-Type: text/html");
  142. if (startGame) {
  143. printWriteOut.println(cookie);
  144. }
  145. printWriteOut.println("\n"); // new line
  146. for (int row=0; row<htmlResponse.length; row++) {
  147. System.err.println(" >>> " + htmlResponse[row]);
  148. printWriteOut.println(htmlResponse[row]);
  149. }
  150.  
  151. // Reset Variables for next request and response
  152. startGame = false;
  153. cookie = cookie.replace("Set-Cookie: JSESSIONID=", "");
  154.  
  155. // Close this request
  156. printWriteOut.close();
  157. System.err.println("We just closed");
  158.  
  159. } catch (IOException e) {
  160. System.err.println(e.getMessage());
  161. }
  162.  
  163. }
  164. } catch (IOException e) {
  165. System.err.println(e.getMessage());
  166. System.err.println("Could not listen on port: " + this.port);
  167. System.exit(1);
  168. }
  169. }
  170. public String GETreader(BufferedReader in, PrintWriter out, String cookie) {
  171. Boolean startGame = true;
  172. String line;
  173. try {
  174. while(in.ready()) {
  175. line = in.readLine();
  176. System.out.println("In function <<< " + line);
  177.  
  178. if(line.contains("Cookie:")==true){
  179. System.out.println("We had the line " + line);
  180. cookie = line.substring(line.length()-13, line.length()); // Retrieve the part of cookie line we use as key
  181. System.out.println("We got this Cookie in the GET request: " + cookie);
  182. startGame = false;
  183. }
  184. }
  185. } catch (IOException e) {
  186. e.printStackTrace();
  187. }
  188.  
  189. System.err.println("Check if not in sessionMap, key: " + cookie);
  190. // if (cookie in HashMap) don't start a new game:
  191. if (!sessionMap.containsKey(cookie)){ startGame = true; System.err.println(cookie + " was not in sessionMap");}
  192.  
  193. // else: new game
  194. if (startGame == true) {
  195. System.err.println("We have a GET request and should start new game");
  196. int correct = (int)(Math.random() * 100 + 1); // Correct Answer
  197. int[] gameInfo = { correct, 0, 1, 100};
  198. String timeStamp = Long.toString(System.currentTimeMillis());
  199. cookie = "Set-Cookie: JSESSIONID="+timeStamp;
  200. sessionMap.put(timeStamp, gameInfo); //cookie = timeStamp;
  201.  
  202. System.err.println("------------------------------");
  203. System.err.println("We started a new game with the following information:");
  204. System.err.println("Correct answer gameInfo[0] = " + String.valueOf(gameInfo[0]));
  205. System.err.println("Min Guess = " + String.valueOf(gameInfo[2]));
  206. System.err.println("Max Guess = " + String.valueOf(gameInfo[3]));
  207. System.err.println("Stored on the Cookie: = " + cookie);
  208. System.err.println("------------------------------");
  209. System.err.println("Put in sessionMap on key: " + timeStamp);
  210.  
  211. }
  212. // Return the cookie that identifies the client who sent the GET request
  213. // So we can send the apropriate respnse for exactly this client
  214. return cookie;
  215.  
  216. }
  217. public String[] POSTreader(BufferedReader in, PrintWriter out, String cookie) {
  218. String line = "";
  219. int guess = 0;
  220. try {
  221. while(in.ready()) {
  222. line = in.readLine();
  223. System.out.println("In function <<< " + line);
  224. if(line.contains("Cookie:")==true) {
  225. cookie = line.substring(line.length()-13, line.length());
  226. }
  227. if(line.equals("")){
  228. break;
  229. }
  230. }
  231. } catch (IOException e) {
  232. e.printStackTrace();
  233. }
  234. int[] client = sessionMap.get(cookie); // [0] = Correct Answer
  235. // [1] = Number of Guesses
  236. // [2] = Min Guess
  237. // [3] = Max Guess
  238. client[1] += 1; // Add 1 number of guesses for each POST request
  239. sessionMap.replace(cookie, client); // Update number of guesses in hashMap
  240. StringBuilder postRequest = new StringBuilder();
  241. try {
  242. // For some reason my loop gets stuck if at the empty line everytime,
  243. // so I have to continue letter by letter from there
  244. while (in.ready()) {
  245. char letter = (char)in.read();
  246. System.out.println("In function <<< " + letter);
  247. postRequest.append(letter);
  248. }
  249. } catch (IOException e) {
  250. e.printStackTrace();
  251. }
  252. String guessString = postRequest.toString().replace("guess=", ""); // Remove all but the number
  253. System.out.println("\n");
  254. System.err.println("Vår gissning är: " + guessString);
  255.  
  256. // Return the guess and the cookie that identifies the client who sent it
  257. String[] stringArray = new String[]{ guessString, cookie };
  258. return stringArray;
  259. }
  260.  
  261. public static String[] readHtmlFile(String path) {
  262. // Read the html file that we use as base for all our responses
  263. String[] html = new String[16];
  264. String line;
  265. try {
  266. FileReader fr = new FileReader(path);
  267. BufferedReader br = new BufferedReader(fr);
  268. int row = 0;
  269. while ((line = br.readLine()) != null){
  270. html[row] = line;
  271. row += 1;
  272. }
  273. br.close();
  274. } catch (FileNotFoundException e) {
  275. System.out.println("Kan inte hitta file: " + path);
  276. } catch (IOException e) {
  277. // Kan inte läsa file
  278. e.printStackTrace();
  279. }
  280. return html;
  281. }
  282.  
  283. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement