Reconnection of Client when server reboots in WebSocket

When the server reboots, the Web Socket connection is closed, so the JavaScript onclose event is triggered. Here’s an example that tries to reconnect every five seconds.

function start(websocketServerLocation){
    ws = new WebSocket(websocketServerLocation);
    ws.onmessage = function(evt) { alert('message received'); };
    ws.onclose = function(){
        // Try to reconnect in 5 seconds
        setTimeout(function(){start(websocketServerLocation)}, 5000);
    };
}

Leave a Comment