可靠的WebSocket连接状态检测 [英] Reliable WebSocket connection state detection

查看:145
本文介绍了可靠的WebSocket连接状态检测的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找实现可靠的WebSocket连接恢复机制的方法.

I've been looking around to implement a reliable WebSocket connection recovery mechanism.

经过一番调查,我发现一种方法是将听音发送到服务器(乒乓/乒乓球),并检查是否在有限的时间内收到了整个 pong .

After some investigation, I've found that one way is sending hearbeats to the server (ping/pong), and check if I receive the whole pong in a limited time.

因此,如果连接确实断开或非常慢,则如果 pong 等待超时,则将被视为断开连接,并且代码应调用 WebSocket.close().

Thus, either if the connection is actually down or it's very slow it would be considered disconnected if a pong wait timeouts, and code should call WebSocket.close().

最终,我要问的问题是使用WebSockets验证连接重新连接工作流程,并检查是否缺少某些内容.

At the end of the day, I'm asking this question to validate the connection-reconnection workflow using WebSockets, and check if I'm missing something.

也就是说,我的问题是这是实现WebSockets重新连接机制的正确且可靠的工作流程吗?

That is, my question is, is this the right and reliable workflow to implement WebSockets reconnection mechanism?

推荐答案

websocket协议为ping和pong定义了特殊的控制帧,但是无法通过JavaScript API进行访问.但是,如果服务器发送这些帧,则浏览器会回答.

The websocket protocol define special control frames for ping and pong, but they are not accessible through the JavaScript API. But if the server send those frames, the browser will answer.

但是,如果连接突然断开并成为半开放连接,尽管服务器会检测到它,但浏览器却不会.因此,我想在应用程序级别发送自己的ping并不是一个坏主意.

However, if the connection is cut suddenly and become an half-open connection, although the server will detect it, the browser won't. So I guess that sending your own pings at application level is not a bad idea.

回答您的问题是的,这是一个好主意,因为如果连接打开了一半,则您的客户端不会获得更新,因为他认为该连接已连接.在websocket中,客户端必须启动连接,因此,即使浏览器意识到断开连接,也无法执行任何重新连接操作.

Answering your question yes, it is good idea because if the connection gets half opened, your client is not getting updates because he thinks it is connected. In websocket, the client has to initiate the connection, so even if the browser realizes the disconnection, there is nothing it can do to reconnect.

这篇关于可靠的WebSocket连接状态检测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆