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:
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) });