3

I am using Azure Pub-Sub Service for Chatting module in a ReactApplication, I am creating this connection using Websocket.

let ws = new WebSocket(token.url);
       ws.onmessage = (data) => {
    //Messages Logic
    }

when i am in other tabs, or in the sametab for longer time(more than 40-45 mins). I am not receiving messages, but when i refresh the page and websocket initialization code gets executed again and then i receive messages again. Any Suggestions?

Manjunath G
  • 167
  • 2
  • 10
  • 1
    Websockets don't live forever, they time out like any other idle network connection. If you walk away from a tab for 45 wholes minutes, add `blur` and `focus` logic that closes the websocket on blur, and reestablishes it on focus. (or use a keepalive message sent every minute or something to artificially keep the connection open, but really: don't. Just close the connection until it's needed again)) – Mike 'Pomax' Kamermans Jun 13 '22 at 04:15

1 Answers1

1

Use this technique :

function connect() {
  var ws = new WebSocket('ws://localhost:8080');
  ws.onopen = function() {
    // subscribe to some channels
    ws.send(JSON.stringify({
        //.... some message the I must send when I connect ....
    }));
  };

 
  ws.onclose = function(e) {
    console.log('Socket is closed. Reconnect will be attempted in 1 second.', e.reason);
    setTimeout(function() {
      connect();
    }, 1000);
  };
Moein Moeinnia
  • 1,945
  • 3
  • 10
  • 26