Keep-alives were added to HTTP to basically reduce the significant overhead of rapidly creating and closing socket connections for each new request. The following is a summary of how it works within HTTP 1.0 and 1.1:
HTTP 1.0 The HTTP 1.0 specification does not really delve into how Keep-Alive should work. Basically, browsers that support Keep-Alive appended an additional header to the request as [edited for clarity] explained below:
When the server processes the request and generates a response, it also adds a header to the response:
Connection: Keep-Alive
When this is done, the socket connection is not closed as before, but kept open after sending the response. When the client sends another request, it reuses the same connection. The connection will continue to be reused until either the client or the server decides that the conversation is over, and one of them drops the connection.
以上解释comes from here .但是我不明白一件事
When this is done, the socket connection is not closed as before, but kept open after sending the response.
据我所知,我们只是发送 tcp 数据包来发出请求和响应,这个 socket 连接
有何帮助以及它是如何工作的?我们仍然需要发送数据包,但它如何以某种方式建立持久连接呢?看起来很不真实。
最佳答案
建立新的 TCP 连接(DNS 查找、TCP 握手、SSL/TLS 握手等)会产生开销。如果没有保持事件状态,每个 HTTP 请求都必须建立一个新的 TCP 连接,然后在发送/接收到响应后关闭连接。 keep-alive 允许将现有的 TCP 连接重新用于多个请求/响应,从而避免所有这些开销。这就是使连接“持久”的原因。
在 HTTP 0.9 和 1.0 中,默认情况下,服务器在向客户端发送响应后关闭其 TCP 连接的末端。客户端必须在收到响应后关闭其 TCP 连接端。在 HTTP 1.0(但不是 0.9)中,客户端可以通过在请求中包含 Connection: keep-alive
header 来明确要求服务器不要关闭其连接端。如果服务器同意,它会在响应中包含一个 Connection: keep-alive
header ,并且不会关闭它的连接端。然后,客户端可以重新使用相同的 TCP 连接来发送其下一个请求。
在 HTTP 1.1 中,keep-alive
是默认行为,除非客户端通过在请求中包含 Connection: close
header 明确要求服务器关闭连接,或者服务器决定在其响应中包含一个 Connection: close
header 。
关于sockets - 详解http保活机制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20763999/