Ajith C Narayanan
Ajith C Narayanan

Reputation: 616

Writing an http server in c with connection persistence support

When I read a request from a browser, the HTTP connection header always comes with a Keep-Alive value, so I kept the connection socket descriptor open after writing a response to the stream. I heard that this causes the client (browser) will reuse the same connection to send the next request.

But the client sends another connect() request to create a new connection for sending the next request.

Why do browsers send keep-alive option with every header?

Upvotes: 0

Views: 2140

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 597016

the client sends another connect() request to create a new connection for sending the next request.

If you are sending an HTTP 1.0 response to an HTTP 1.0/1.1 request:

  • the default behavior is Connection: close unless a Connection: keep-alive response header is sent (only if the client sends a Connection: keep-alive request header!). If you do not send that, the client will have no choice but to close the connection and make a new one each time.

If you are sending an HTTP 1.1 response to an HTTP 1.1 request:

  • the default behavior is Connection: keep-alive unless a Connection: close response header is sent, so make sure you are not sending that unless the client sends a Connection: close request header, or you are intentionally closing the connection.

Either way, if the connection is going to be kept alive after the response has been sent, consider also including a separate Keep-Alive response header to inform compatible clients of when the connection will timeout and be closed if the client does not re-use it before the timeout elapses (and then be sure to actually implement that timeout in your server code). For example:

Connection: keep-alive
Keep-Alive: timeout=300

why do browsers send keep-alive option with every header?

Because it is a per-request feature. Any request can ask to keep the connection alive, and the server has to acknowledge it each time. Once a connection has been closed, it is gone.

Upvotes: 2

Related Questions