WebSocket: How to automatically reconnect after it dies WebSocket: How to automatically reconnect after it dies javascript javascript

WebSocket: How to automatically reconnect after it dies


Here is what I ended up with. It works for my purposes.

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.onmessage = function(e) {    console.log('Message:', e.data);  };  ws.onclose = function(e) {    console.log('Socket is closed. Reconnect will be attempted in 1 second.', e.reason);    setTimeout(function() {      connect();    }, 1000);  };  ws.onerror = function(err) {    console.error('Socket encountered error: ', err.message, 'Closing socket');    ws.close();  };}connect();


This worked for me with setInterval, because client connection can be lost.

ngOnInit(): void {    if (window.location.protocol.includes('https')) {        this.protocol = 'wss';    }    this.listenChanges();}listenChanges(): void {    this.socket = new WebSocket(`${this.protocol}://${window.location.host}/v1.0/your/url`);    this.socket.onmessage = (event): void => {        // your subscription stuff        this.store.dispatch(someAction);    };    this.socket.onerror = (): void => {        this.socket.close();    };    this.socket.onopen = (): void => {        clearInterval(this.timerId);        this.socket.onclose = (): void => {            this.timerId = setInterval(() => {                this.listenChanges();            }, 10000);        };    };}

Don't forget to call clearInterval when the socket has been opened.


A too interesting wrapper above the native Websocket api to add that and nicely

https://github.com/joewalnes/reconnecting-websocket