NodeJS Websocket how to reconnect when server restarts

后端 未结 4 2071
轮回少年
轮回少年 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: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: ...,
    });
    

提交回复
热议问题