简体   繁体   English

Socket.io - 离开房间时延迟

[英]Socket.io - delay when leaving a room

I want to send the number of users connected to a room when a client leaves. 我想在客户离开时发送连接到房间的用户数量。

It seems socket.leave() has a delay. 似乎socket.leave()有延迟。

How to do that properly? 怎么做得好? I don't like to use setTimeout() 我不喜欢使用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 is asynchronous, and as such has an optional second parameter for a callback, so you could do this: 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
});

...which should report the correct number ...应报告正确的数字

This requires the latest version of Socket.io (version 1.0) which has not yet been published to npm (as of 11/14/2013). 这需要最新版本的Socket.io(版本1.0)尚未发布到npm(截至2013年11月14日)。 To use it, you'd need to include the following in your package.json: 要使用它,您需要在package.json中包含以下内容:

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

...which should pull in the 1.0 branch (caveat stability). ...应该拉入1.0分支(警告稳定性)。

io.sockets.manager.roomClients[socket.id] returns a list of rooms with leading '/' character in all room names. io.sockets.manager.roomClients[socket.id]返回所有房间名称中带有前导'/'字符的房间列表。

The Socket.io Wiki says : "This is used internally and does not have to be referenced when joining, leaving or emitting to rooms." Socket.io Wiki说: “这是在内部使用的,在加入,离开或发射到房间时不必引用。”

So, When you leave a room, make sure that the room name does not contain the leading '/' character. 因此,当您离开房间时,请确保房间名称不包含前导'/'字符。 You can try socket.leave(room.replace('/','')); 你可以尝试socket.leave(room.replace('/',''));

Not tested, but should do the trick. 没有测试,但应该做的伎俩。

You can check working example of displaying number of clients in this repository. 您可以查看在此存储库中显示客户端数量的工作示例。 It is developed for socket.io v1.0 and express v4.0. 它是为socket.io v1.0和express v4.0开发的。

https://github.com/theoctal/livenote https://github.com/theoctal/livenote

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM