【问题标题】:Disconnect event fire after 2 minutes2 分钟后断开连接事件触发
【发布时间】:2015-03-25 06:30:11
【问题描述】:

我正在使用 node.js 和 socket.io 创建一个聊天应用程序。

socket.on('disconnect',function(data){
    console.log("disconnected");
}

一旦客户端断开连接(选项卡关闭或网络问题),就会触发此事件。

我希望在与客户端断开连接 1 分钟后触发断开连接事件。那可能吗? socket.io里面有配置吗?

【问题讨论】:

  • 为什么会有用?在收到断开连接事件后添加自己的超时一分钟很容易。
  • 如果 socket.io 中已经有一个选项,我可以使用它而不是编写自己的超时函数。

标签: node.js socket.io


【解决方案1】:

socket.io 中没有内置该功能。当套接字断开连接时会触发 disconnect 事件。时期。如果您想在断开连接 1 分钟后触发某些活动,您可以构建自己的计时器来执行此操作。

socket.on('disconnect',function(data){
    setTimeout(function() {
        console.log("disconnected");
    }, 60 * 1000);
}

如果您只想在客户端未在 1 分钟内重新连接时触发您的事件,那么您也可以编写代码,但它涉及更多一点,因为您必须保存 setTimeout() 的计时器,然后取消如果该特定客户端在计时器触发之前重新连接。


根据您在回答中的内容,我认为这是一个改进的版本:

(function() {
    var origClose = socket.onclose;
    socket.onclose = function(reason){
      var self = this;
      var args = Array.prototype.slice.call(arguments);

      /* Delay of 1 second to remove from all rooms and disconnect the id */
      setTimeout(function() {
          origClose.apply(self, args);
      }, 60 * 1000);
    }
})();

【讨论】:

    【解决方案2】:

    Socket.onclose 在断开连接事件之前断开连接后立即触发。 可以通过如下更改来延迟断开连接事件。

    socket.onclose = function(reason){
      console.log(socket.adapter.sids[socket.id]);
      Object.getPrototypeOf(this).onclose.call(this,reason);
    
      /* Delay of 1 seconds to remove from all rooms and disconnect the id */
      setTimeout(function() {
          if (!this.connected) return this;
          debug('closing socket - reason %s', reason);
          this.leaveAll();
          this.nsp.remove(this);
          this.client.remove(this);
          this.connected = false;
          this.disconnected = true;
          delete this.nsp.connected[this.id];
          this.emit('disconnect', reason);
      }, 60 * 1000);
    }
    

    【讨论】:

    • 为什么在setTimeout() 之前调用常规的onclose()?这不会导致断开事件立即触发吗?这不是违背了你正在做的事情的目的吗?难道你不能在超时时调用prototype.onclose,而不是复制你正在复制的所有代码,如果实现发生变化,这些代码将来很容易中断?我知道您对此有何看法,看来您可以朝这个方向解决您的问题,但是您发布的代码看起来不正确。
    • 看看我在我之前回答的最后写了什么,我认为这是一个改进的版本。仅供参考,您的将无法正常工作,因为 thissetTimeout() 回调中不正确。
    【解决方案3】:

    你有一些参数来控制服务器端的这种行为。见close timeoutheartbeat timeouthere 如果您使用的是 v1.0,则需要以here. 描述的新样式设置选项

    请注意,这些在技术上并不能满足您的要求 - 它们只是延长了客户端必须重新连接的时间。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-20
      • 2014-04-03
      • 2018-01-28
      • 1970-01-01
      • 2016-05-22
      • 2018-09-20
      • 1970-01-01
      相关资源
      最近更新 更多