javascriptreactjswebsocketchatazure-web-pubsub

React Websocket gets inactive after some time


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?


Solution

  • 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);
      };