Socket.io - 离开房间时延迟

Socket.io - delay when leaving a room

本文关键字:时延 延迟 房间 离开 io Socket      更新时间:2023-09-26

我想在客户离开时发送连接到房间的用户数量。

看来socket.leave()有延迟。

如何正确地做到这一点?我不喜欢使用 setTimeout()

socket.on('disconnect', function () {
  var roomsToSayGoodbye = io.sockets.manager.roomClients[socket.id];
  for (var room in roomsToSayGoodbye) {
    io.sockets.in(room).clients().length; // For example: 6
    socket.leave(room);
    io.sockets.in(room).clients().length; // Still 6!!
    // So, this is wrong -->
    io.sockets.in(room).emit('nb-connections', { num: io.sockets.in(room).clients().length });
    // <--
    // and I need this to make it work, not clean! -->
    setTimeout(function() {
      io.sockets.in(room).clients().length; // Okay, now 5
    }, 1000 );
  }
}

> Socket.leave 是异步的,因此有一个可选的第二个参数用于回调,因此您可以这样做:

socket.leave(room, function() {
    io.sockets.in(room).emit('nb-connections', { num: io.sockets.in(room).clients().length });
    // this should be the number you want
});

。哪个应该报告正确的数字

这需要最新版本的 Socket.io(版本 1.0),该版本尚未发布到 npm(截至 2013 年 11 月 14 日)。 要使用它,您需要在 package.json 中包含以下内容:

"dependencies": {
    "socket.io": "git://github.com/LearnBoost/socket.io.git#1.0"
}

。这应该拉入 1.0 分支(警告稳定性)。

>io.sockets.manager.roomClients[socket.id]返回所有聊天室名称中具有前导'/'字符的聊天室列表。

Socket.io 维基说:"这是内部使用的,在加入、离开或发射到房间时不必引用。

因此,当您离开房间时,请确保房间名称不包含前导'/'字符。你可以试试socket.leave(room.replace('/',''));

没有经过测试,但应该可以解决问题。

您可以查看显示此存储库中客户端数量的工作示例。它是针对 socket.io v1.0 和 express v4.0 开发的。

https://github.com/theoctal/livenote

相关文章: