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

前端 未结 4 1238
星月不相逢
星月不相逢 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.

    0 讨论(0)
  • 2020-12-04 06:39

    Start reconnecting even if the first attempt fails

    If the first connection attempt fails, socket.io 0.9.16 doesn't try to reconnect for some reason. This is how I worked around that.

    //if this fails, socket.io gives up
    var socket = io.connect();
    
    //tell socket.io to never give up :)
    socket.on('error', function(){
      socket.socket.reconnect();
    });
    
    0 讨论(0)
  • 2020-12-04 06:40

    I know this has an accepted answer, but I searched forever to find what I was looking for and thought this may help out others.

    If you want to let your client attempt to reconnect for infinity (I needed this for a project where few clients would be connected, but I needed them to always reconnect if I took the server down).

    var max_socket_reconnects = 6;
    
    var socket = io.connect('http://foo.bar',{
        'max reconnection attempts' : max_socket_reconnects
    });
    
    socket.on("reconnecting", function(delay, attempt) {
      if (attempt === max_socket_reconnects) {
        setTimeout(function(){ socket.socket.reconnect(); }, 5000);
        return console.log("Failed to reconnect. Lets try that again in 5 seconds.");
      }
    });
    
    0 讨论(0)
  • 2020-12-04 06:48

    edit: Socket.io has builtin-support now

    When I used socket.io the disconnect did not happen(only when i closed the server manually). But you could just reconnect after say for example 10 seconds on failure or something on disconnect event.

    socket.on('disconnect', function(){
       // reconnect
    });
    

    I came up with the following implementation:

    client-side javascript

    var connected = false;
    const RETRY_INTERVAL = 10000;
    var timeout;
    
    socket.on('connect', function() {
      connected = true;
      clearTimeout(timeout);
      socket.send({'subscribe': 'schaftenaar'});
      content.html("<b>Connected to server.</b>");
    });
    
    socket.on('disconnect', function() {
      connected = false;
      console.log('disconnected');
      content.html("<b>Disconnected! Trying to automatically to reconnect in " +                   
                    RETRY_INTERVAL/1000 + " seconds.</b>");
      retryConnectOnFailure(RETRY_INTERVAL);
    });
    
    var retryConnectOnFailure = function(retryInMilliseconds) {
        setTimeout(function() {
          if (!connected) {
            $.get('/ping', function(data) {
              connected = true;
              window.location.href = unescape(window.location.pathname);
            });
            retryConnectOnFailure(retryInMilliseconds);
          }
        }, retryInMilliseconds);
      }
    
    // start connection
    socket.connect();
    retryConnectOnFailure(RETRY_INTERVAL);
    

    serverside(node.js):

    // express route to ping server.
    app.get('/ping', function(req, res) {
        res.send('pong');
    });
    
    0 讨论(0)
提交回复
热议问题