Reliable WebSocket connection state detection

a 夏天 提交于 2020-12-01 10:53:27

问题


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

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.

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().

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.

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


回答1:


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.

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.

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.



来源:https://stackoverflow.com/questions/24605873/reliable-websocket-connection-state-detection

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