0

How do the options of my socket (socket, which I've got after accept() ) related to HTTP header "Connection: Keep-Alive"? I know, that if I want to keep my socket alive, I need to set the following options: SO_KEEPALIVE, TCP_KEEPIDLE, TCP_KEEPINTVL, and TCP_KEEPCNT. For instance, if I want to wait for 10 seconds and then send 10 probes maximum with an interval of 2 seconds, before dropping the connection, I will write something like this:

int yes = 1;
setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, &yes, sizeof(int);

int idle = 10;
setsockopt(sock, IPPROTO_TCP, TCP_KEEPIDLE, &idle, sizeof(int));

int interval = 2;
setsockopt(sock, IPPROTO_TCP, TCP_KEEPINTVL, &interval, sizeof(int));

int maxpkt = 10;
setsockopt(sock, IPPROTO_TCP, TCP_KEEPCNT, &maxpkt, sizeof(int));

And if I intend to keep the connection open for at most five more transactions, or until it has sat idle for two minutes, I will send the next headers within my response:

Connection: Keep-Alive
Keep-Alive: max=5, timeout=120

It's all OK, but I don't understand how these things relate to each other. How should I add supporting of Keep-Alive attribute to my HTTP-server?

I will be grateful for any help. Thank you in advance.

  • Does this answer your question? [HTTP Keep Alive and TCP keep alive](https://stackoverflow.com/questions/9334401/http-keep-alive-and-tcp-keep-alive). In short - HTTP keep-alive and TCP keep alive are completely unrelated mechanisms which do different things. They only sound similar, but that's all. – Steffen Ullrich Jul 17 '20 at 14:25
  • Oh, thank you! Does it mean, that to implement keep-alive on my HTTP server, I need only to send corresponding headers with my response and then count the number of requests in current connection and time elapsed since the connection became idle? – Olexandr Kulinich Jul 17 '20 at 14:44
  • *" ... that to implement keep-alive on my HTTP server ..."* - assuming you mean HTTP keep-alive and not TCP keep alive here. Just sending the header is not enough and even sending the headers at all is not needed since it is implicit behavior with HTTP/1.1 anyway. And HTTP keep-alive is only a proposal, the peer can the close the connection at any time after a request+response is finished. – Steffen Ullrich Jul 17 '20 at 15:23

0 Answers0