Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Name: ADDISON HO BOON WEE
- Student number: A0168530E
- Is this a group submission (yes/no)?: NO
- If it is a group submission:
- Name of 2nd group member: THE_OTHER_NAME_HERE_PLEASE
- Student number of 2nd group member: THE_OTHER_NO
- */
- import java.net.*;
- import java.nio.ByteBuffer;
- import java.nio.file.*;
- import java.io.*;
- import java.util.*;
- import java.util.Timer;
- public class WebServer {
- public static void main(String[] args){
- // dummy value that is overwritten below
- int port = 8080;
- try {
- port = Integer.parseInt(args[0]);
- } catch (Exception e) {
- System.out.println("Usage: java WebServer <port> ");
- System.exit(0);
- }
- WebServer serverInstance = new WebServer();
- try {
- serverInstance.start(port);
- } catch(IOException e){
- System.out.println(e);
- }
- }
- private void start(int port) throws IOException{
- System.out.println("Starting server on port " + port);
- ServerSocket serverSocket = new ServerSocket(port);
- while(true){
- Socket clientSocket = serverSocket.accept();
- handleClientSocket(clientSocket, serverSocket);
- }
- }
- /**
- * Handles requests sent by a client
- * @param client Socket that handles the client connection
- */
- private void handleClientSocket(Socket client, ServerSocket server) throws IOException {
- try {
- boolean socket = true;
- BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
- String line;
- while(socket){
- while((line = in.readLine()) != null && !line.isEmpty()){
- String[] header = line.split(" ");
- String[] host = in.readLine().split(" ");
- String file = "";
- if (header[1].indexOf("/") == 0){
- file = header[1].substring(1);
- }
- if(header[0].equals("GET")){
- sendHttpResponse(client, formHttpResponse(new HttpRequest(file, header[2], host[1])));
- if(header[2].equals("HTTP/1.1")){
- client.setSoTimeout(2000);
- }else{
- socket = false;
- }
- }else{
- socket = false;
- }
- }
- }
- } catch (SocketTimeoutException e) {
- System.out.println("Closing socket..");
- } finally {
- client.close();
- }
- }
- /**
- * Sends a response back to the client
- * @param client Socket that handles the client connection
- * @param response the response that should be send to the client
- */
- private void sendHttpResponse(Socket client, byte[] response) throws IOException {
- OutputStream out = client.getOutputStream();
- out.write(response);
- }
- /**
- * Form a response to an HttpRequest
- * @param request the HTTP request
- * @return a byte[] that contains the data that should be send to the client.
- */
- private byte[] formHttpResponse(HttpRequest request) throws IOException {
- //Form the HTTP response by joining all headers, note the CRLF and SP delimiters.
- byte[] file = Files.readAllBytes(Paths.get(request.getFilePath()));
- String ContentLength = String.format("Content Length: %d\r\n\r\n",file.length);
- String StatusLine = String.format("%s 200 OK\r\n", request.getMethod());
- return concatenate(concatenate(StatusLine.getBytes(), ContentLength.getBytes()), file);
- }
- /**
- * Concatenates 2 byte[] into a single byte[]
- * This is a function provided for your convenience.
- * @param buffer1 a byte array
- * @param buffer2 another byte array
- * @return concatenation of the 2 buffers
- */
- private byte[] concatenate(byte[] buffer1, byte[] buffer2) {
- byte[] returnBuffer = new byte[buffer1.length + buffer2.length];
- System.arraycopy(buffer1, 0, returnBuffer, 0, buffer1.length);
- System.arraycopy(buffer2, 0, returnBuffer, buffer1.length, buffer2.length);
- return returnBuffer;
- }
- }
- /**
- * HttpRequest encapsulates a packet transmitted by the client and its information.
- * This packet can be accessed to from response messages by the server.
- */
- class HttpRequest {
- //Filepath of requested object.
- private String filePath;
- //Method i.e. GET, POST requested by client.
- private String method;
- //Host location of the object.
- private String host;
- /**
- * Constructor.
- *
- * @param new_filePath (required) filepath of requested object.
- * @param new_method (required) method name to perform on object.
- * @param new_host (required) host location of object.
- */
- public HttpRequest(String new_filePath, String new_method, String new_host){
- this.filePath = new_filePath;
- this.method = new_method;
- this.host = new_host;
- }
- String getFilePath() {
- return this.filePath;
- }
- String getMethod(){
- return this.method;
- }
- String getHost(){
- return this.host;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement