NodeJS Websocket how to reconnect when server restarts

Try this:

var reconnectInterval = x * 1000 * 60;
var ws;
var connect = function(){
    ws = new WebSocket('ws://localhost');
    ws.on('open', function() {
        console.log('socket open');
    });
    ws.on('error', function() {
        console.log('socket error');
    });
    ws.on('close', function() {
        console.log('socket close');
        setTimeout(connect, reconnectInterval);
    });
};
connect();

You get to use the original implementation without having to wrap it.

Leave a Comment