我如何知道与 websockets 的连接是否有效? [英] How do i know if connection is alive with websockets?
问题描述
我有一个 web 应用程序,它在浏览器中运行.该 webapp 连接到使用 websockets 的服务器.所以服务器和我的客户端/浏览器之间的通信是基于 websockets 的.如果服务器上发生了一些神奇的事件,一些 Web 服务会向我的 Web 应用程序发送一个新的 XML/JSON 并显示新数据.
I have a webapp, which is running in a browser. That webapp is connected to a server, which uses websockets. So the communication between the server and my client/browser is based on websockets. If some magic event occurs on the server, some webservice sends a new XML / JSON to my webapp and the new data gets displayed.
但是,作为客户端/浏览器,我如何知道连接是否还活着?假设我在大约 30 秒内没有收到任何新的 XML.我怎么知道连接是关闭/断开/服务器离线还是一切正常,但服务器本身没有发生新的魔法事件.
But how do i, as the client / browser, know if the connection is stil alive? Lets say i do not get any new XML for about 30 seconds. How would i know if the connection is closed/broken/server offline or everything is fine, but on the server himself no new magic event occured.
推荐答案
3 种方式:
- 依赖 TCP 来检测连接丢失,最终会在 JS onclose 事件中弹出
- 从服务器发送 WebSocket ping .. 浏览器将回复 WS pongs,在客户端也可能更可靠地检测到连接丢失
- 从浏览器向服务器发送应用级别的心跳,服务器需要有逻辑来回复.您无法从浏览器(在 JS 中)触发 WS ping
这篇关于我如何知道与 websockets 的连接是否有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!