I want to create keep-alive connection, which should not close. I tried below way but it is closing after date get printed.
public class SimplePHTTPServer {
public static void main(String args[]) throws IOException {
ServerSocket server = new ServerSocket(1122);
System.out.println("Listening for connection on port 1122 ....");
while (true) {
try (Socket socket = server.accept()) {
Date today = new Date();
String httpResponse = "HTTP/1.1 200 OK\r\n\r\n" + today;
socket.getOutputStream().write(httpResponse.getBytes("UTF-8"));
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Tested through curl below is the actual output:
curl -i -X GET -H "Connection: keep-alive" http://localhost:1122/
HTTP/1.1 200 OK
Thu Aug 02 18:42:30 IST 2018
expected result is :
curl -i -X GET -H "Connection: keep-alive" http://localhost:1122/
HTTP/1.1 200 OK
Thu Aug 02 18:42:30 IST 2018
Thu Aug 02 18:47:30 IST 2018
Thu Aug 02 18:52:30 IST 2018
... so on
How to create keep-alive connection?
You mistake the purpose of the persistent connection. It allows you to make multiple requests and get multiple responses over one connection.
In your test, you send one request and you're trying to provide an unlimited length response body.
The way you try to provide unlimited length response body is not correct. Please read this RFC, paying special attention to "transfer coding". Some choice quotes:
...
...
...
...