将 Socket.IO v.1.3.5
用于node.JS ...
如何获得房间内连接的真实用户数量(非会话)?
var room = io.sockets.adapter.rooms[roomId] || {};
var numSocketsInRoom = Object.keys(room).length;
但是,如果在多个浏览器选项卡中连接了相同的用户,则numSocketInRoom会增加,因为会话数而不是实际用户数。
在我的情况下,任何套接字都将用户保存在socket.userId
中,但我不知道如何指出这样可以获得在一个房间内连接的用户数...
谢谢!
答案 0 :(得分:0)
我的解决方案最终是这段代码,此代码在加入(isConnect = true
)或离开(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;