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

Dan*_*Dan 37 node.js

我正在使用node.js和socket.io构建一个小型原型.一切都运行良好,我面临的唯一问题是我的node.js连接将断开连接,我被迫刷新页面,以便连接并再次运行.

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

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

非常感谢,Dan

nor*_*gon 90

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

例如(这些是默认值):

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

这就是我做的:

socket.on('disconnect', function () {
  console.log('reconnecting...')
  socket.connect()
})
socket.on('connect_failed', function () {
  console.log('connection failed. reconnecting...')
  socket.connect()
})
Run Code Online (Sandbox Code Playgroud)

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


Alf*_*red 20

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

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

socket.on('disconnect', function(){
   // reconnect
});
Run Code Online (Sandbox Code Playgroud)

我想出了以下实现:

客户端的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);
Run Code Online (Sandbox Code Playgroud)

服务器端(的node.js):

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

  • `window.location.href = unescape(window.location.pathname)`做什么? (3认同)

abs*_*tor 5

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

如果第一次连接尝试失败,则出于某种原因,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();
});
Run Code Online (Sandbox Code Playgroud)