getting how many people are in a chat room in socket.io
If you're using version < 1,
var clients = io.sockets.clients(nick.room); // all users from room
For socket.io versions >= 1.0:
Note that rooms became actual types with a .length
property in 1.4, so the 1.4.x method should be stable from now on. Barring breaking changes to that type's API, of course.
To count all clients connected to 'my_room'
:
1.4+:
var room = io.sockets.adapter.rooms['my_room'];
room.length;
1.3.x:
var room = io.sockets.adapter.rooms['my_room'];
Object.keys(room).length;
1.0.x to 1.2.x:
var room = io.adapter.rooms['my_room'];
Object.keys(room).length;
This is assuming you're running with the default room adapter on a single node (as opposed to a cluster). Things are more complicated if you're in a cluster.
Other related examples:
Count all clients connected to server:
var srvSockets = io.sockets.sockets; Object.keys(srvSockets).length;
Count all clients connected to namespace
'/chat'
:var nspSockets = io.of('/chat').sockets; Object.keys(nspSockets).length