原文:https://blog.csdn.net/bdss58/article/details/77800813 ,略有改动。

Table of Contents

HTTP keep-alive

HTTP 1.0 中,Connection 请求头的值是 close:

Connection: close

从 HTTP 1.1 协议开始,Connection 的值默认为 keep-alive:

Connection: keep-alive

这意味着,HTTP client 可以复用一个连接来多次发起请求或接收消息。HTTP client 向 HTTP server 发起一个请求,建立一个新的连接,HTTP server 根据请求头中的 Connection: keep-alive,在返回消息后并不会立即断开连接(本次 HTTP 请求所建立的 TCP 连接),而是等待一段时间再关闭 TCP 连接。在这段时间内,HTTP client 可以在这个 TCP 连接上继续发送请求。

等待时长 timeout 的值可以在 HTTP client 和 HTTP server 中指定。比如在 HTTP client 请求头(request header)中加入:

Keep-Alive: timeout=5, max=1000

表示让 HTTP server 保持连接 5 秒钟,本次连接最大请求数 1000 次。如果 HTTP server 也设置了 Keep-Alive 的 timeout 值,那么以两者最小的时间为准。比如 HTTP server 设置了 timeout=3,则会在返回头(response header)中添加:

Keep-Alive: timeout=3, max=1000

这次连接会在接收到最后一次请求后的 3 秒钟,被 HTTP server 断开。

TCP keepalive

TCP keepalive 是传输层的功能,和应用层的 HTTP keep-alive 是两个完全不同的概念

TCP keepalive 指的是一端通过发送小的数据包(keepalive probe packet)给另一端,来维持 TCP 连接。

What is TCP keepalive?

The keepalive concept is very simple: when you set up a TCP connection, you associate a set of timers. Some of these timers deal with the keepalive procedure. When the keepalive timer reaches zero, you send your peer a keepalive probe packet with no data in it and the ACK flag turned on. You can do this because of the TCP/IP specifications, as a sort of duplicate ACK, and the remote endpoint will have no arguments, as TCP is a stream-oriented protocol. On the other hand, you will receive a reply from the remote host (which doesn't need to support keepalive at all, just TCP/IP), with no data and the ACK set.

If you receive a reply to your keepalive probe, you can assert that the connection is still up and running without worrying about the user-level implementation. In fact, TCP permits you to handle a stream, not packets, and so a zero-length data packet is not dangerous for the user program.

This procedure is useful because if the other peers lose their connection (for example by rebooting) you will notice that the connection is broken, even if you don't have traffic on it. If the keepalive probes are not replied to by your peer, you can assert that the connection cannot be considered valid and then take the correct action.