gpt4 book ai didi

node.js - 套接字IO : Number of users in a room

转载 作者:太空宇宙 更新时间:2023-11-03 22:33:45 24 4
gpt4 key购买 nike

对node.JS使用Socket.IO v.1.3.5...

如何获取房间中连接的真实用户(非 session )数量?

session 数:

 var room = io.sockets.adapter.rooms[roomId] || {};
var numSocketsInRoom = Object.keys(room).length;

但是,如果同一用户在多个浏览器选项卡中连接,则 numSocketInRoom 会增加,因为 numSocketInRoom 是 session 数,而不是真实的用户数。

就我而言,任何套接字都将用户保存在 socket.userId 中,但我不知道如何指示它来获取房间中连接的用户数量...

谢谢!

最佳答案

我的解决方案最终是这段代码,这段代码在 join (isConnect = true) 或 leave (isConnect = false)房间:

//Get the room:
var room = io.sockets.adapter.rooms[roomId] || {};
//Declaration of number of users variable
var numUsers;

//If there are any user connected in the room, create the object
if(room.user===undefined)
room.user = {};

//If you join the room and have another opened session, increase the number of sessions
if(room.user[socket.request.user.id] && isConnect)
room.user[socket.request.user.id] += 1;

//If you leave the room and have another opened session, decrease the number of sessions
else if(room.user[socket.request.user.id] && !isConnect){
room.user[socket.request.user.id] -= 1;

//If the number of sessions is 0, delete the user from the object
if(room.user[socket.request.user.id]===0)
delete room.user[socket.request.user.id];
}
//If the user don't have any session and join the room, put 1 session in the object
else if(isConnect){
room.user[socket.request.user.id] = 1;
}

//Get the number of users from room.user object
numUsers = Object.keys(room.user).length;

关于node.js - 套接字IO : Number of users in a room,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33078182/

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