Advertisement
Guest User

Untitled

a guest
Feb 19th, 2018
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.14 KB | None | 0 0
  1. /*
  2. Name: ADDISON HO BOON WEE
  3. Student number: A0168530E
  4. Is this a group submission (yes/no)?: NO
  5.  
  6. If it is a group submission:
  7. Name of 2nd group member: THE_OTHER_NAME_HERE_PLEASE
  8. Student number of 2nd group member: THE_OTHER_NO
  9. */
  10.  
  11. import java.net.*;
  12. import java.nio.ByteBuffer;
  13. import java.nio.file.*;
  14. import java.io.*;
  15. import java.util.*;
  16. import java.util.Timer;
  17.  
  18. public class WebServer {
  19. public static void main(String[] args){
  20. // dummy value that is overwritten below
  21. int port = 8080;
  22. try {
  23. port = Integer.parseInt(args[0]);
  24. } catch (Exception e) {
  25. System.out.println("Usage: java WebServer <port> ");
  26. System.exit(0);
  27. }
  28.  
  29. WebServer serverInstance = new WebServer();
  30. try {
  31. serverInstance.start(port);
  32. } catch(IOException e){
  33. System.out.println(e);
  34. }
  35. }
  36.  
  37. private void start(int port) throws IOException{
  38. System.out.println("Starting server on port " + port);
  39. ServerSocket serverSocket = new ServerSocket(port);
  40. while(true){
  41. Socket clientSocket = serverSocket.accept();
  42. handleClientSocket(clientSocket, serverSocket);
  43. }
  44. }
  45.  
  46. /**
  47. * Handles requests sent by a client
  48. * @param client Socket that handles the client connection
  49. */
  50. private void handleClientSocket(Socket client, ServerSocket server) throws IOException {
  51. try {
  52. boolean socket = true;
  53. BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
  54. String line;
  55. while(socket){
  56. while((line = in.readLine()) != null && !line.isEmpty()){
  57.  
  58. String[] header = line.split(" ");
  59. String[] host = in.readLine().split(" ");
  60. String file = "";
  61.  
  62. if (header[1].indexOf("/") == 0){
  63. file = header[1].substring(1);
  64. }
  65.  
  66. if(header[0].equals("GET")){
  67. sendHttpResponse(client, formHttpResponse(new HttpRequest(file, header[2], host[1])));
  68. if(header[2].equals("HTTP/1.1")){
  69. client.setSoTimeout(2000);
  70. }else{
  71. socket = false;
  72. }
  73. }else{
  74. socket = false;
  75. }
  76. }
  77. }
  78. } catch (SocketTimeoutException e) {
  79. System.out.println("Closing socket..");
  80. } finally {
  81. client.close();
  82. }
  83. }
  84.  
  85. /**
  86. * Sends a response back to the client
  87. * @param client Socket that handles the client connection
  88. * @param response the response that should be send to the client
  89. */
  90. private void sendHttpResponse(Socket client, byte[] response) throws IOException {
  91. OutputStream out = client.getOutputStream();
  92. out.write(response);
  93. }
  94.  
  95. /**
  96. * Form a response to an HttpRequest
  97. * @param request the HTTP request
  98. * @return a byte[] that contains the data that should be send to the client.
  99. */
  100. private byte[] formHttpResponse(HttpRequest request) throws IOException {
  101. //Form the HTTP response by joining all headers, note the CRLF and SP delimiters.
  102. byte[] file = Files.readAllBytes(Paths.get(request.getFilePath()));
  103. String ContentLength = String.format("Content Length: %d\r\n\r\n",file.length);
  104. String StatusLine = String.format("%s 200 OK\r\n", request.getMethod());
  105. return concatenate(concatenate(StatusLine.getBytes(), ContentLength.getBytes()), file);
  106. }
  107.  
  108.  
  109. /**
  110. * Concatenates 2 byte[] into a single byte[]
  111. * This is a function provided for your convenience.
  112. * @param buffer1 a byte array
  113. * @param buffer2 another byte array
  114. * @return concatenation of the 2 buffers
  115. */
  116. private byte[] concatenate(byte[] buffer1, byte[] buffer2) {
  117. byte[] returnBuffer = new byte[buffer1.length + buffer2.length];
  118. System.arraycopy(buffer1, 0, returnBuffer, 0, buffer1.length);
  119. System.arraycopy(buffer2, 0, returnBuffer, buffer1.length, buffer2.length);
  120. return returnBuffer;
  121. }
  122. }
  123.  
  124. /**
  125. * HttpRequest encapsulates a packet transmitted by the client and its information.
  126. * This packet can be accessed to from response messages by the server.
  127. */
  128. class HttpRequest {
  129.  
  130. //Filepath of requested object.
  131. private String filePath;
  132. //Method i.e. GET, POST requested by client.
  133. private String method;
  134. //Host location of the object.
  135. private String host;
  136.  
  137. /**
  138. * Constructor.
  139. *
  140. * @param new_filePath (required) filepath of requested object.
  141. * @param new_method (required) method name to perform on object.
  142. * @param new_host (required) host location of object.
  143. */
  144. public HttpRequest(String new_filePath, String new_method, String new_host){
  145. this.filePath = new_filePath;
  146. this.method = new_method;
  147. this.host = new_host;
  148. }
  149.  
  150. String getFilePath() {
  151. return this.filePath;
  152. }
  153.  
  154. String getMethod(){
  155. return this.method;
  156. }
  157.  
  158. String getHost(){
  159. return this.host;
  160. }
  161. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement