Created
February 7, 2022 15:06
-
-
Save sakshamgurung/fa7ebe33fe25816f96d63442ae33966b to your computer and use it in GitHub Desktop.
Connection class part II
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// continue Connection class... | |
// overiding run method from Thread class | |
public void run(){ | |
// Initializing a Scanner class to read stream input from the | |
// socket connection between server and client | |
Scanner scan = new Scanner(this.in, "UTF-8"); | |
try{ | |
// separating the HTTP request header from rest of the HTTP message | |
// "\\r\\n\\r\\n" below refers to the 'empty line' from fig.1 | |
String requestHeader = scan.useDelimiter("\\r\\n\\r\\n").next(); | |
System.out.println("*********Header Data***********"); | |
System.out.println("*******************************"); | |
System.out.println(requestHeader); | |
System.out.println("*******************************\n\n"); | |
// decomposing request header to understand client request message | |
String[] headerLines = requestHeader.split("\r\n"); | |
String[] startLine = headerLines[0].split(" "); | |
String method = startLine[0]; // GET method | |
String path = startLine[1]; // index.html | |
String version = startLine[2]; // HTTP version | |
// handling GET request from the client | |
if (method.equals("GET")) { | |
// calling helper method to search and get the path that | |
// leads to the resource client is looking for | |
Path filePath = getFilePath(path); | |
System.out.println("file path: " + filePath); | |
// checking if resource path exists | |
if (Files.exists(filePath)) { | |
// file exist | |
// calling helper method to guess the file extension | |
// type like .html, .mp4, etc | |
String contentType = guessContentType(filePath); | |
System.out.println("file exist"); | |
System.out.println("content type:" + contentType); | |
// calling helper method and setting standard HTTP | |
// status code, response type, and response content | |
sendResponse("200 OK", contentType, "", Files.readAllBytes(filePath)); | |
} else { | |
// file not found | |
System.out.println("File not found"); | |
byte[] notFoundContent = "<h1> File not found :( </h1>".getBytes("UTF-8"); | |
sendResponse("404 Not Found", "text/html", "", notFoundContent); | |
} | |
out.flush(); | |
break; | |
} | |
} catch(Exception e) { | |
System.out.println("EOF:"+e); | |
} finally { | |
scan.close(); | |
try { | |
clientSocket.close(); | |
}catch (IOException e){ | |
/*close failed*/ | |
} | |
} | |
} | |
// continue... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment