Node.js and Socket.IO - How to reconnect as soon as disconnect happens

前端 未结 4 1252
星月不相逢
星月不相逢 2020-12-04 06:29

I\'m building a small prototype with node.js and socket.io. Everything is working well, the only issue I\'m facing is that my node.js connection will disconnect and I\'m fo

4条回答
  •  无人及你
    2020-12-04 06:34

    EDIT: socket.io now has built-in reconnection support. Use that.

    e.g. (these are the defaults):

    io.connect('http://localhost', {
      'reconnection': true,
      'reconnectionDelay': 500,
      'reconnectionAttempts': 10
    });
    

    This is what I did:

    socket.on('disconnect', function () {
      console.log('reconnecting...')
      socket.connect()
    })
    socket.on('connect_failed', function () {
      console.log('connection failed. reconnecting...')
      socket.connect()
    })
    

    It seems to work pretty well, though I've only tested it on the websocket transport.

提交回复
热议问题