I am using a SockJS client side library to connect to a server which is using SockJS node js library.
When the web page refreshes everytime it makes a new web socket connection with the server. And the previous connection does not get disconnected. So if there is 5 refreshes there would be 5 different web socket connections.
How can I check if a web socket connection is active and prevent new connections from creating or disconnect existing connection on page reload or in a network disconnection?
I am using a SockJS client side library to connect to a server which is using SockJS node js library.
When the web page refreshes everytime it makes a new web socket connection with the server. And the previous connection does not get disconnected. So if there is 5 refreshes there would be 5 different web socket connections.
How can I check if a web socket connection is active and prevent new connections from creating or disconnect existing connection on page reload or in a network disconnection?
Share Improve this question asked Nov 26, 2016 at 12:40 rkshrksh 4,05010 gold badges52 silver badges72 bronze badges2 Answers
Reset to default 3Each new page is its own new context, and everything from the old context gets discarded browser-side. So there is no way to preserve a WebSocket connection across page loads.
In your situation, on the browser side you actually only have a single WebSocket connection at any time: That established by the newly reloaded page.
The problem on the server side is that there is no way to differentiate a disconnect from an inactive/very slow connection if there is no traffic.
One way around this is to use heartbeats, i.e. a regular ping/pong of messages between the server and the browser. WebSocket supports this at the protocol level, and server-side WebSocket libraries should expose this mechanism. This is useful in any case since it works irrespective of how the disconnect happens (e.g. for network failures).
For a reload you should attach a handler to the relevant event (beforeunload
) and then do a clean disconnect. You'd catch this with the heartbeat as well, but this way you can react before the next heartbeat fails.
You can't prevent this situation, but you can do heartbeats from the Web Socket server to detect stale clients and drop the connection from the server-side.
Perhaps you can take a look at this MDN tutorial:
At any point after the handshake, either the client or the server can choose to send a ping to the other party. When the ping is received, the recipient must send back a pong as soon as possible. You can use this to make sure that the client is still connected, for example.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745393652a4625780.html
评论列表(0条)