How to send message to room clients when a client disconnects

I want the server to send a message to all room clients when one of them disconnects.

Something like this:

socket.on('disconnect', function() {
    server.sockets.in(room).emit('bye');
});

But...

  • How do I know which room to broadcast?
  • What if the client has joined to multiple rooms?

After inspecting the sockets object, I came up with this solution:

socket.on('disconnect', function() {
    var rooms = io.sockets.manager.roomClients[socket.id];
    for (var room in rooms) {
        if (room.length > 0) { // if not the global room ''
            room = room.substr(1); // remove leading '/'
            console.log('user exits: '+room);
            server.sockets.in(room).emit('bye');
        }
    }
});

not 100% on this - but give it a try:

when connecting to a room or adding a new user to the mix, remember their username or id or something in the socket:

socket.on('adduser', function(username){
    socket.username = username;
    socket.join('room');
}

Then listen to leave events on rooms:

socket.room.on('leave', function(){
    socket.broadcast.to(this).emit(socket.username + ' says seeya!');
}

It's worth a try anyway - I'm sure something similar will work if this doesn't.