在什么情况下需要关闭 HTTP 连接?

2022-01-24 00:00:00 connection http php

在什么情况下需要关闭 HTTP 连接?

In What conditions are closing a HTTP connection necessary?

推荐答案

HTTP 不是具有连接"的协议类型;这就是他们所说的无状态",这意味着每个请求都与其他请求分开.这就是为什么我们有会话cookie之类的东西;人们必须以某种方式进行黑客攻击,以允许信息在请求之间传递.

HTTP isn't the type of protocol to have "connections"; it's what they call "stateless", meaning each request is separate from every other request. That's why we have things like session cookies; people had to hack in a way to allow information to be carried over between requests.

现在,即使它们是分开的,HTTP 1.1 也允许客户端通过同一个 TCP/IP 连接发出多个请求(虽然它是到 HTTP 服务器的连接,但在 TCP/IP 栈).这些请求仍然是分开的,但您不必打开新的网络连接.这可以提高一些效率,因为打开网络连接可能会很昂贵.

Now, even though they're separate, HTTP 1.1 allows a client to make multiple requests over the same TCP/IP connection (which, although it's a connection to an HTTP server, is at a whole other level in the TCP/IP stack). The requests will still be separate, but you don't have to open a new network connection. This allows some efficiency gains, as opening a network connection can be expensive.

如果您想利用这一点,请查看请求和响应中的标头.如果请求使用的 HTTP 版本低于 1.1,或者标头显示 Connection: close,则在处理完当前请求后,连接就会消失.否则,一旦它被清除(通常通过读取上一个请求中的所有数据),它就可以被重用.

If you'd like to take advantage of this, watch the headers in the request and response. If the request is using an HTTP version less than 1.1, or there's a header that says Connection: close, then the connection is to go away after the current request is handled. Otherwise, once it's been cleared out (usually by reading all the data from the previous request), it can be reused.

相关文章