2 分钟后断开事件触发

Disconnect event fire after 2 minutes

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

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

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

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

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

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

您有一些参数可以在服务器端控制此行为。参见 close timeoutheartbeat timeout here 如果您使用的是 v1.0,则需要以 here.

描述的新样式设置选项

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

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