Node.js & Socket.IO - Rooms issue

Considering a multi-chat application. Users can join multiple rooms ( socket.join(room) ), users can leave a room ( socket.leave(room) ).

When socket is leaving a room I notify the other room participants. If the socket is currently in 3 rooms, and he suddenly disconnects from the website without leaving the rooms the proper way, how can I notify those rooms that the user has left ?

If I work with the on socket disconnect event, the user will no longer be in any room at that point. Is the only way keeping a separate array of users, or is there some clever way I haven't thought about?

During the disconnect event the socket is still available to your process. For example, this should work

io.socket.on('connection', function(socket){
    socket.on('disconnect', function() {
       // this returns a list of all rooms this user is in
       var rooms = io.sockets.manager.roomClients[socket.id];
       for(var room in rooms) {
           socket.leave(room);
       }
    });
});

Although this is not actually necessary as socket.io will automatically prune rooms upon a disconnect event. However this method could be used if you were looking to perform a specific action.

I'm assuming that socket is a long lived object in your node process. If that's the case then you could easily add a reference to the user on your socket object when the user connects. When you get a socket disconnect, you don't need to look up the user the session is associated with as it will be there.

on connection or login:

socket.user = yourUser;

on disconnect:

socket.on('disconnect', function(){
  socket.leave(room, socket.user);
}

see here for an example of adding properties to the socket object and a single room chat client:

http://psitsmike.com/2011/09/node-js-and-socket-io-chat-tutorial/