您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

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

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

我想出了以下实现:

@H_404_5@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);

@H_404_5@// express route to ping server.
app.get('/ping', function(req, res) {
    res.send('pong');
});
Node 2022/1/1 18:14:10 有572人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶