I am writing a simple web server in Java with the help of ServerSocket and Socket APIs provided by JDK. I have a WebServer class(a 'Thread') which has a
ServerSocket serverSocket = new ServerSocket(8086);
and blocks on
Socket clientSocket = serverSocket.accept();
I have a fixed thread pool executor with the WebServer class. When a client connects and unblocks the .accept() call, I create an instance of Connection class (a 'Runnable' and implemented by me to process requests and respond back to client). This instance is passed to the fixed thread pool executor to execute. The loop in the WebServer class is as shown below:
while(!Thread.interruped()) {
try {
final Socket client = this.serverSocket.accept();
logger.debug("WebServer: Incoming request!!");
final Connection connection = new Connection(client, this.rootPath);
this.threadPool.execute(connection);
} catch (IOException e) {
logger.error("Error listening on " + this.port + " because " + e.getMessage());
}
}
I also have a simple form in an html to 'POST' data to the server. The form html is as given below:
<html>
<body>
<h1>Blog post</h1>
<form id="blogPost" method="post" action="/POSTrequest">
Title: <input type="text" name="title"></input><br />
Text: <input type="text" name="text"></input><br />
<input type="submit" value="Submit" name="Submit">
</form>
</body>
</html>
Considering it is HTTP/1.1 (keep-alive behaviour), which I have assured, and I have to implement in this application, there are 2 issues now:
1.) Every time I send a GET request from the web browser to fetch the above html, to submit the form (and actually post the data), I need to click it twice (this is not a double click). In the first click the request headers are empty (when I parse the request line by line). It is in the second click on the button, that the data is posted well and can be well processed on the server side. All subsequent clicks (until I refresh the page) are served in one click.
2.) In all the clicks as I mentioned in point 1. the web page is waiting indefinitely on the server (localhost in my case) for a response, while, according to me I have written and flushed, the appropriate response (200 OK with other headers, including Connection:keep-alive and the correct length in Content-Length).
3.) Also I observe, while responding back on a POST request, even after having the header Connection:keep-alive, and not having to close the socket or the in/out streams of the socket, there is another request coming from the client(the web page) to connect (possibly a trait of HTTP/1.1 to have a persistent connection). Why is this happening, when neither the socket was closed nor the streams, nor was the keep-alive header missed.
Sorry for putting up multiple problems in this post. Please put up your questions, as more details could be required. Thanks for help!
Also any helpful links to socket programming in Java with HTTP/1.1?