【问题标题】:Node.js and Socket.IO - How to reconnect as soon as disconnect happensNode.js 和 Socket.IO - 如何在断开连接后立即重新连接
【发布时间】:2011-05-24 20:29:50
【问题描述】:

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

有没有办法在断开事件触发后立即重新建立连接?

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

非常感谢, 丹

【问题讨论】:

标签: node.js


【解决方案1】:

编辑:socket.io 现在有built-in reconnection support。使用它。

例如(这些是默认值):

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

这就是我所做的:

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

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

【讨论】:

【解决方案2】:

我知道这是一个公认的答案,但我一直在寻找我正在寻找的东西,并认为这可能对其他人有所帮助。

如果您想让您的客户端无限尝试重新连接(我需要这个用于连接很少客户端的项目,但如果我关闭服务器,我需要它们始终重新连接)。

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

【讨论】:

  • "reconnectionAttempts":"Infinity"
【解决方案3】:

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

如果第一次连接尝试失败,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();
});

【讨论】:

  • 谢谢,这个对我有用(但我使用 socket.socket.connect(); 而不是重新连接)!
【解决方案4】:

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

当我使用 socket.io 时,没有发生断开连接(仅当我手动关闭服务器时)。但是您可以在失败或断开连接事件发生 10 秒后重新连接。

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

我想出了以下实现:

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

服务器端(node.js):

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

【讨论】:

  • 重新连接套接字就好了。另外,你永远不会设置timeout
  • @Nornagon 我重新连接到套接字?同样在您的实现中,您只需尝试再次连接到套接字。但是您断开连接是有原因的?
  • @Alfred - 你重新加载整个网页。我确实因为某种原因断开了连接,但我仍然想继续重试,直到那个原因消失(即服务器重新启动:))
  • @Nornagon 我不会重新加载整个网页。你甚至用过代码吗?我使用简单的 ajax 请求来测试 web 服务的可用性!
  • window.location.href = unescape(window.location.pathname) 是做什么的?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-21
  • 1970-01-01
  • 1970-01-01
  • 2020-02-07
  • 1970-01-01
相关资源
最近更新 更多