简体   繁体   中英

Keep WebSocket connection alive after refresh

I have a real time application which used WebSockets between java spring server and browser. Is there a method to keep the Websocket connection alive after page refresh ?

This is my javascript code:

consumerWebSocket = new WebSocket("wss://" + window.location.host + 
"/myWebSocketConnection");

consumerWebSocket.onopen = function () {
    sendThroughWS(consumerWebSocket, "Send this message from browser to server");

};

No, you cannot. The problem is that the context a websockets lives in is limited to the page you are displaying. As soon as you refresh the page or navigate to another, the context (and therefore the websocket) is destroyed.

A solution to prevent destroying is to create some sort of Single page Application. The new content would be loaded into the existing page and the websocket is not reloaded.

Another way is using frames. You can put your Websocket in a (hidden) frame and just navigate using another frame. This way the socket can be stay alive and you can navigate through the rest of your page without a websocket reload.

1. On every refresh new socket connection will be created the problem is not new socket but will the rest of the application use this new socket connection to communicate with your client or a previous connection??

So this above is the riddle to solve , to tell the rest of the application that Hey: forget my last connection instance, use this new one instead

  1. Communications on your chat application or whatever should be persisted on database with your users id or users/friend relationship you've chosen

  2. Sometimes its important to store reference of your socket connection to some sort of persistence layer Redis might work, even on other database its okey. on close of connection mark that instance reference as close on refresh so you have new socket, then update the socket instance reference on your persistence layer( some sort of db )

  3. Once your application wants to send message to you it go through the db and if they find the open reference to your socket connection then the socket is used to send you a message if no reference or closed, then the text/messages are stored on database.

  4. When you've refreshed a webpage or new socket is connected then the client side browser should request the chats/message from database from backend, through that very socket => Mind some pagination, not to load tones of text on one request

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM