2

I am using javascript websocket and want it to reconnect onclose with code 1006. I came across this

Reconnection of Client when server reboots in WebSocket

the accepted answer there does work but after 20 seconds when the server reconnects the number of attempted connections rise to 4 and the user receives 4 messages which was actually sent only once.

The 20 seconds is just a number, the loss of connection could be server side issue or a client internet issue.

I hope I have been clear in describing the issue Regards, Shyam

Community
  • 1
  • 1
Shyam Sundar
  • 21
  • 1
  • 2

1 Answers1

1

You can watch on your close event error code and reconnect

var ws = null; //reserve it for websocket

function connectWebsocket(){ 
    if ("WebSocket" in window) //browser supports webscokets
    {
        ws = new WebSocket("ws://your_url");
        ws.addEventListener("open", socketOpened);
        ws.addEventListener("message", messageRecived);
        ws.addEventListener("close", socketClosed);
     }else // browser doesn't support chat.. 
     {
        alert("Websockets not supported by browser ");
     }
 };
 function socketClosed(evt){ 
       switch(evt.code){
            case 1006: 
                setTimeout(connectWebsocket,1000); //try to reconnect in 1s
                break;

        }
   };
Marko Mackic
  • 2,293
  • 1
  • 10
  • 19