轮询和网络套接字中的连接

Connections in polling and web sockets

我对网络开发还很陌生,对一些概念感到困惑。具体来说,我不确定长轮询和网络套接字之间有什么区别。

长轮询是否涉及为每个请求启动到服务器的新 TCP 连接,或者是否存在用于完成轮询的持久 TCP 连接?如果我理解正确,我认为 WebSockets 允许持久的 TCP 连接,其中数据在服务器和客户端之间交换,并且此连接的持续时间在 headers 中提到。

任何comments/help将不胜感激。

长轮询是客户端向服务器发送http请求。如果服务器有可用于请求的数据,它 returns 立即将数据作为 http 响应并完成连接。

如果服务器立即没有任何数据,那么它会在连接上挂起一段时间(设计为小于典型的客户端超时)。如果数据在时间限制之前到达,则 http 响应与数据一起发送,连接完成。

如果在时间限制到期之前服务器中没有新数据可用,则服务器 returns 响应它还没有数据并且该 http 套接字已完成。此时,客户端在新套接字上发出新请求并重新开始整个过程​​。

Does long polling involve initiating a new TCP connection to the server for each request or is there a persistent TCP connection over which polling is done?

每次都是新连接。这就是轮询效率不是特别高的原因。

If I understood it right, I think WebSockets allow the persistent TCP connection where data is exchanged between server and client and the duration of this connection is mentioned in the headers.

webSocket 被设计为持久连接,可以持续很长时间,然后客户端或服务器可以随时发送数据。与 http 请求相比,webSocket 连接有额外的设置,但一旦建立,与长轮询相比效率更高。

这些参考资料中解释了更多信息:

HTML5 WebSocket: A Quantum Leap in Scalability for the Web