为什么在没有数据传输时,EventSource 连接每隔 30-60 秒关闭一次,而 WebSocket 连接保持打开状态?
我想每 2 分钟向用户推送一次数据。使用 EventSource 需要每 29 秒额外推送一次空字节以保持连接打开。 WebSocket 不需要这样的 ping。为什么EventSource连接会定期关闭并重新打开?是因为HTTP中没有好的内置方法来检查连接是否仍然打开还是其他原因?
I would like to push data to users every 2 min. Using EventSource requires additional pushing null-byte every 29 sec to keep the connection open. WebSocket doesn't require such ping. Why is the EventSource connection regularly closed and reopened? Is it because there is no good built-in way in HTTP to check if the connection is still open or other reason?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
服务器发送的事件 (Eventsource) API 位于 HTTP 之上。 WebSocket 位于 TCP 之上(但具有 HTTP 兼容的握手)。 HTTP 和TCP 通常都有空闲超时,但是TCP 超时往往要长得多(例如2 小时而不是2 分钟)。因此,您可能仍然需要 WebSocket 中的保持活动消息,但它们的频率可能要低得多。此外,WebSocket 标准定义了浏览器/服务器可以实现的 ping/pong 帧为你做这件事。
The Server-Sent Events (Eventsource) API is layered on HTTP. WebSocket is layered on TCP (but has an HTTP compatible handshake). Both HTTP and TCP often have idle timeouts however, the TCP timeouts tend to be much longer (e.g. 2 hours rather than 2 minutes). So you still might need keep-alive messages in WebSockets, but they could probably be much less frequent. Also, the WebSocket standard defines ping/pong frames that the browser/server may implement to do this for you.
这可能取决于您的服务器端软件
node.js有2分钟的默认超时
这里是关于它的文章 - http://contourline.wordpress.com/2011/03/30/preventing-server-timeout-in-node-js/
解决方案:
res.connection.setTimeout(0); // 这可能需要一段时间
it may depend on your server-side software
node.js has 2 minutes default timeout
here is article about it - http://contourline.wordpress.com/2011/03/30/preventing-server-timeout-in-node-js/
solution:
res.connection.setTimeout(0); // this could take a while