So after establishing my listening for a connection and accepting one:
ServerSocket serverSock = new ServerSocket(6789);
Socket sock = serverSock.accept();
When I type into my browser localhost:6789/index.html how do I handle this incoming GET request and return index.html? index.html is in the same directory.
Firstly I want to very that index.html actually exists and if not I return a HTTP 404 message. Then I will close the connection.
Handling GET and other requests is actually very simple but you must know the specification of the HTTP protocol.
The first thing to do is to get the
SocketInputStreamof the client and the path of the file to return. The first line of the HTTP request comes in this form:GET /index.html HTTP/1.1. Here is a code example that does that:You create a new
Fileobject and checks if that file exists. If the file does not exist, you return a 404 response to the client. Otherwise you read the file and send its content back to the client:Here is the complete code summary: