Node.js 和 Socket.IO - 如何在断开连接后立即重新连接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4432271/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 13:45:57  来源:igfitidea点击:

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

node.js

提问by Dan

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 forced to refresh the page in order to get the connection up and running again.

我正在用 node.js 和 socket.io 构建一个小原型。一切正常,我面临的唯一问题是我的 node.js 连接将断开连接,我被迫刷新页面以重新启动并运行连接。

Is there a way to reestablish the connection as soon as the disconnect event is fired?

一旦断开连接事件被触发,有没有办法重新建立连接?

From what I've heard, this is a common issue. So, I'm looking for a best-practice approach to solving this problem :)

据我所知,这是一个普遍的问题。所以,我正在寻找解决这个问题的最佳实践方法:)

Thanks very much, Dan

非常感谢,丹

采纳答案by Alfred

edit: Socket.io has builtin-support now

编辑:Socket.io 现在有内置支持

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.io 时,断开连接没有发生(仅当我手动关闭服务器时)。但是您可以在说例如失败 10 秒或断开连接事件后重新连接。

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

I came up with the following implementation:

我想出了以下实现:

client-side javascript

客户端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):

服务器端(node.js):

// express route to ping server.
app.get('/ping', function(req, res) {
    res.send('pong');
});

回答by nornagon

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

编辑:socket.io 现在有内置的重新连接支持。用那个。

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()
})
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.

它似乎工作得很好,虽然我只在 websocket 传输上测试过它。

回答by abstraktor

Start reconnecting even if the first attempt fails

即使第一次尝试失败也开始重新连接

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

如果第一次连接尝试失败,socket.io 0.9.16不会出于某种原因尝试重新连接。这就是我解决这个问题的方式。

//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();
});

回答by Applehat

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.");
  }
});