Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to maintain a WebSockets connection between pages?

On one of my scripts I have this code:

var webSocket = window.WebSocket || window.MozWebSocket; window.ws = new webSocket('ws://64.121.210.140:2585/consoleappsample', 'my-protocol'); 

Which works fine. However, when the user changes pages, I have to re-establish the connection. I believe this is causing problems in my code because if the client sends data to the server and then changes pages, the data may not be received and race conditions are occurring.

I tried to put the window.ws in global scope but it didn't seem to fix the problem. Is there any way for the WebSockets connection to persist between pages so the connection does not need to be constantly reestablished?

like image 250
Ryan Peschel Avatar asked Jun 04 '12 19:06

Ryan Peschel


People also ask

How do you maintain a WebSocket connection between pages?

Another old approach could be put your pages in a frame, where the user navigate only in the frame (even if it takes the whole size of the window). In that way, you can create your WebSocket in the top most window, that is never changed (that also means the URL showed in the location bar will be always the same).

Do WebSockets reconnect automatically?

clear-ws handles reconnects automatically (if you provide not null reconnect.

Why do WebSockets disconnect?

WebSocket disconnects can happen by choice, or due to exceptional/error conditions. Here is some information about what happens in each case: Clean disconnect: During a clean disconnect, the user or application will initiate a disconnect sequence.


1 Answers

The global scope you mentioned is always related to the JavaScript Context, and a Context is created for each windows (and destroyed when the document is unloaded from the memory). Therefore, your effort are useless: you can't keep a connection opened if the user change page. Of course you can have your webapp as "single page" application, where all the data are loaded using XMLHttpRequest / ajax / WebSocket. So, leaving the page means leaving / shutdown the application, and makes sense close the socket.

Another old approach could be put your pages in a frame, where the user navigate only in the frame (even if it takes the whole size of the window). In that way, you can create your WebSocket in the top most window, that is never changed (that also means the URL showed in the location bar will be always the same).

Said that, I agreed with @dystroy: your application should be always able to handle this scenario - the user could have some network problem and lost the connection for a moment, even if it doesn't leave the page.

like image 139
ZER0 Avatar answered Oct 11 '22 06:10

ZER0