You should read the RFC regarding Keep-Alive. Otherwise, you may end up on a server that is not working properly.
As @ [Stephen] already pointed out, the server can close the connection at any time it wants (normally, but not in the middle of a request / response pair). The same goes for the customer. Any other solution will allow the server or client to perform DoS on the other side.
EDIT: look at the Connection header. The client (and server) can request a graceful closing of the connection using the header. For example, Connection: close inside a request is a request to the server to close the connection after sending the response.
Alexander
source share