Under what circumstances will my browser attempt to re-use a TCP connection for multiple requests?

巧了我就是萌 提交于 2019-12-17 22:24:52

问题


I am using Firefox, but I'd like to know how browsers decide this in general.

It seems that when I access the same URL twice in a short amount of time, my browser tries to re-use the TCP same connection for both requests (this is called keep-alive). However, when I access two different URLs (but still served by the same server), the browser sometimes decides to open up a new connection for each request. Obviously, the browser does not use a one-connection-per-URL policy.

I am asking this because I am trying to implement a web service that uses long polling. I can imagine that a user might want to open this service in multiple tabs on the same browser. However, with keep-alive, the second long poll request does not get sent until the first one completes (at least in Firefox), because the browser is trying to shove both of them into the same socket, which I did not expect when I designed the service. Even if the browser implements pipe-lining, there is no way that I can respond to the second request before I respond to the first, because HTTP mandates that I complete the responses in order.


回答1:


When using HTTP/1.1, by default, the TCP connections are left open for reuse. This is for better performance than starting a new connection per request. The connection can be reused but the connection could close at any time by any of the parties.

You should read HTTP1.1 and the part on persistent connections.

In your case it is not even using HTTP pipelining (not broadly supported) because the next request is sent after the response of the first.

The browsers have a connection pool and reuse it per hostname. Generally speaking, a browser should not reuse a single connection for multiple hostnames, even if those hostnames actually resolve to the same IP address.

Most browsers allow the user to configure or override the number of persistent connections per server; most modern browsers default to six. If Firefox is truly blocking the second request because there's already a connection active, this is a bug in Firefox and should be filed in their bug tracking system. But if such a bug existed, I think you'd see many sites broken.



来源:https://stackoverflow.com/questions/7310339/under-what-circumstances-will-my-browser-attempt-to-re-use-a-tcp-connection-for

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!