2

I'm trying to count the total number of users in a specific room and broadcast it to all the people in that room.

Here is what I have but I get an error:

var clients = io.sockets.clients(cc.lowerCase(data.roomname)).length;
         io.sockets.in(cc.lowerCase(data.roomname)).emit('updatetotal', { total: clients });

ERROR:

TypeError: Object #<Namespace> has no method 'clients'

Thanks.

1
  • can you show some more code this is not enough to debug the issue
    – azero0
    Commented Jun 8, 2014 at 18:46

2 Answers 2

2

Since socket.io 1.0 its API was significantly changed so the old code might not work.

To get the number of clients in a room you can use this function:

var getUsersInRoomNumber = function(roomName, namespace) {
    if (!namespace) namespace = '/';
    var room = io.nsps[namespace].adapter.rooms[roomName];
    if (!room) return null;
    var num = 0;
    for (var i in room) num++;
    return num;
}

or more laconically:

var getUsersInRoomNumber = function(roomName, namespace) {
    if (!namespace) namespace = '/';
    var room = io.nsps[namespace].adapter.rooms[roomName];
    if (!room) return null;
    return Object.keys(room).length;
}

This function takes two agruments:

  • roomName
  • namespace (optional) default = '/'

To send message to users of this room only use .to method:

io.to(yourRoomName).emit('updatetotal', { total: getUsersInRoomNumber(yourRoomName) });
1
  • but the question is the number of users, not the number of sockets (sessions). If the same user have 3 or 4 browser tabs, this number of users will be 3 or 4... But real connected users only 1.
    – Aral Roca
    Commented Oct 12, 2015 at 9:41
0

to get total users in a room

io.sockets.adapter.rooms.get(roomName).size

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.