NodeJS Websocket how to reconnect when server restarts

后端 未结 4 2076
轮回少年
轮回少年 2020-12-09 10:15

In Node.js I\'m using websockets/ws for a WebSocket connection. Below is the code for the client. Let\'s say the server socket we are connecting to goes down for a minute. T

4条回答
  •  一个人的身影
    2020-12-09 10:54

    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.

提交回复
热议问题