Home > database >  C socket HTTP 1.1 persistent connection when should server close the socket?
C socket HTTP 1.1 persistent connection when should server close the socket?

Time:10-27

I have a simple web server using raw C, which tries to implement the "keep-alive" feature of HTTP 1.1. However, is there any way to know how long the server should wait if the client does not specify extra information? Below are examples about the HTTP GET request from the browser to get localhost:9999/, and the response from the server. The browser does not send any extra request after the first one, but the server still has to keep the connection open.

//request
GET / HTTP/1.1
Host: localhost:9999
Connection: keep-alive
Cache-Control: max-age=0
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36
Accept: text/html,application/xhtml xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Sec-Fetch-Site: none
Sec-Fetch-Mode: navigate
Sec-Fetch-User: ?1
Sec-Fetch-Dest: document
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9


//response
HTTP/1.1 200 OK
Content-Type: text/html

<html><head><style>body{font-family: monospace; font-size: 14px;}td {padding: 2px 7px;}</style></head><body><table>
<tr><td><a href="ctpl.h">ctpl.h</a></td><td>2021-10-27 09:38</td><td>9.8K</td></tr>
<tr><td><a href="M_files/">M_files/</a></td><td>2021-10-24 16:23</td><td>[DIR]</td></tr>
</table></body></html>

In this case, what should the server do next? Should it just ignores the connection (and closes it after some time) or ask the client to close it ?

CodePudding user response:

but the server still has to keep the connection open.

HTTP keep-alive does not mandate the connection to be kept open. Both client and server can close an idle connection at any time, i.e. after request and response are done.

Both client and server can profit though from keeping the connection open, since this decreases the overhead of new requests. But keeping too much connections open has also its costs specifically at the server, since it costs memory and other resources. Thus usually the server will close an idle connection after some time or if some resource limits are reached.

... or ask the client to close it

There is no way for the server to ask the client, except initiating the TCP close.

  • Related