gpt4 book ai didi

javascript - Socket.io - 离开房间时延迟

转载 作者:行者123 更新时间:2023-11-30 10:25:05 24 4
gpt4 key购买 nike

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

似乎 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(截至 11/14/2013)。要使用它,您需要在 package.json 中包含以下内容:

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

...应该引入 1.0 分支(注意稳定性)。

关于javascript - Socket.io - 离开房间时延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19971597/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com