NodeJS Websocket how to reconnect when server restarts

后端 未结 4 2002
轮回少年
轮回少年 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:37

    You should consider a migration to socket.io.

    1. It has built-in auto-reconnect functionality. And you don't have to do anything for it. It is already enabled by default.
    2. Surprisingly, it is compatible with older browsers, even browsers that don't support native websockets.

    The code of both is very similar, but the socket.io is perhaps just a little shorter. e.g. for the server code we used to write something like this:

    const WebSocketServer = require('websocket').server
    const ws = new WebSocketServer({ httpServer });
    ws.on('request', (request) => onConnection(request));
    
    function onConnectionRequest(request) {
      const connection = request.accept(null, request.origin);
      if (!connection) return;
      connection.on('message', (msg) => onMessageReceived(msg));
      connection.on('close', () => onConnectionClosed());
    }
    
    function onMessage(message) {
      if (message.type === 'utf8') {
        const data = message.utf8Data;
        const request = JSON.parse(data);
        // todo use request
      }
    }
    

    Socket.io code is very similar, but just a little shorter.

    const io = require('socket.io')(httpServer);
    io.on('connection', (socket) => onConnection(socket));
    
    function onConnection(socket) {
      socket.on('message', (msg) => onMessage(msg));
      socket.on('disconnect', (reason) => onDisconnect(reason));
    }
    
    function onMessage(request) {
      // todo use request
    }
    

    However, do take in mind, that you also have to rewrite the client code. e.g. For Angular I use the ngx-socket-io plugin, which simplifies the code extremely.

    0 讨论(0)
  • 2020-12-09 10:43

    2018-Jan update

    Reconnecting to a disconnected web socket is non-trivial, and best delegated to a library. The smallest and most actively maintained library for this purpose at the moment is reconnecting-websocket, which obsoletes joewalnes's library from the other answer. For Node.js specifically, you need to pass a constructor, such as WebSocket:

    import WebSocket from 'ws';
    import ReconnectingWebSocket from 'reconnecting-websocket';
    const ws = new ReconnectingWebSocket('wss://some-feed.com', [], {
      constructor: WebSocket,
      connectionTimeout: ...,  // in milliseconds
      reconnectInterval: ...,
    });
    
    0 讨论(0)
  • 2020-12-09 10:44

    I've used https://github.com/joewalnes/reconnecting-websocket/blob/master/reconnecting-websocket.js with success.

    You should be able to do:

    ws = new ReconnectingWebSocket('ws://....');
    ws.reconnectInterval = 60000; // try to reconnect after 10 seconds
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题