套接字IO:一个房间中的用户数

时间:2015-10-12 09:52:36

标签: node.js socket.io

Socket.IO v.1.3.5用于node.JS ...

如何获得房间内连接的真实用户数量(非会话)?

会话数:

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

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

在我的情况下,任何套接字都将用户保存在socket.userId中,但我不知道如何指出这样可以获得在一个房间内连接的用户数...

谢谢!

1 个答案:

答案 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;