Search code examples
javahttpwebserverserversocket

Java: coding for persistent connections


So I'm creating a web server. I think I've got everything pretty much good to go, but the one thing that is baffling me is persistent connections. I've got the logic set up so that it will detect if 'Close connection' was specified. If so it will close the connection and open a new one. Otherwise it will detect that connection should be kept alive. Where I'm getting lost is how to implement keeping the connection alive.

The server will read each line of the header and, after doing so (and after writing the requested information), it will funnel into one of these two statements depending on whether we want to persist the connection:

if (!keepAlive) {

System.out.println("close");
clientSocket.close();
in.close();
write.close();

}else{
System.out.println("keep alive");
}

This if-else statement comes within a continuous while loop. I think I've got the non-persist part set up correctly. Any advice on how to implement persistence?


Solution

  • All you have to do is loop reading requests, instead of just reading a single one. Set a read timeout so you don't get stuck there indefinitely. Break out of the loop if you read EOS instead of a request, or if Connection: close was specified.