Is it possible to listen for join and leave events on a room?

I understand this question is old, but for anyone that stumbles upon this via a google search, this is how I'm approaching it.

Joining a room is something that is pretty easy to account for, even though there aren't native events for joining or leaving a room.

/* client.js */
var socket = io();
socket.on('connect', function () {
    // Join a room
    socket.emit('joinRoom', "random-room");
});

And for the server-side

/* server.js */
// This will have the socket join the room and then broadcast 
// to all sockets in the room that someone has joined
socket.on("joinRoom", function (roomName) {
    socket.join(roomName);
    io.sockets.in(roomName).emit('message','Someone joined the room');
}

// This will have the rooms the current socket is a member of
// the "disconnect" event is after tear-down, so socket.rooms would already be empty
// so we're using disconnecting, which is before tear-down of sockets
socket.on("disconnecting", function () {
    var rooms = socket.rooms;
    console.log(rooms);
    // You can loop through your rooms and emit an action here of leaving
});

Where it gets a bit trickier is when they disconnect, but luckily a disconnecting event was added that happens before the tear down of sockets in the room. In the example above, if the event was disconnect then the rooms would be empty, but disconnecting will have all rooms that they belong to. For our example, you'll have two rooms that the socket will be a part of, the Socket#id and random-room

I hope this points someone else in the right direction from my research and testing.


In Socket.IO, a "room" is really just a namespace, something to help you filter your giant bag of sockets down to a smaller bag of sockets. Calling io.sockets.in('room').on('something') will cause the event handler to fire for every socket in the room when the event fires. If that's what you want, something like this should do the trick:

var room = io.sockets.in('some super awesome room');
room.on('join', function() {
  console.log("Someone joined the room.");
});
room.on('leave', function() {
  console.log("Someone left the room.");
});

socket.join('some super awesome room');
socket.broadcast.to('some super awesome room').emit('join');

setTimeout(function() {
  socket.leave('some super awesome room');
  io.sockets.in('some super awesome room').emit('leave');
}, 10 * 1000);

Important to note is that you'd get the same effect if you (1) got a list of all sockets in a room and (2) iterated over them, calling emit('join') on each. Thus, you should make sure that your event name is specific enough that you won't accidentally emit it outside the "namespace" of a room.

If you only want to emit/consume a single event when a socket joins or leaves a room, you'll need to write that yourself, as, again, a room isn't a "thing" as much as it's a "filter".