How To Find All Users In A Socket.IO Room

Socket.IO version 1.0+ is a complete rewrite of the popular JavaScript library for “real-time bidirectional event-based communication”. This means that a whole lot of your pre-1.0 code will simply not work; it seems they were not concerned with backwards-compatibility at all when they released 1.0.  Because of this, I’ve started writing micro-tutorials on how to do useful, albeit poorly documented, functions of Socket.IO version 1.0 and above.

 

The Objective

On one of my projects, I really needed to know the names and count of how many sockets were connected to a dynamically created set of rooms.  That way I could find out if a room had one person there already (someone waiting for others) or if the room already had too many people in it (to enforce active user quotas).

I wrote a small function (below) that takes a Room argument and an optional Namespace argument.  It will find all of the Socket IDs within the room within the namespace and return an array of those IDs.  With the returned array you can then go on to use those IDs to find the actual socket object using something like io.sockets.connected[member];  Hint: If you are not using namespaces at all and you are taking bits and pieces from this guide, you can change io.nsps[nsp].adapter.rooms[room] to io.sockets.adapter.rooms[room].

 

The Code

/* 'room' (string) is required
 * '_nsp' (string) is optional, defaults to '/'
 * returns an array of Socket IDs (string) */

function getAllRoomMembers(room, _nsp) {
    var roomMembers = [];
    var nsp = (typeof _nsp !== 'string') ? '/' : _nsp;

    for( var member in io.nsps[nsp].adapter.rooms[room] ) {
        roomMembers.push(member);
    }

    return roomMembers;
}

Pin It on Pinterest

Share This