Salvador Dali Salvador Dali - 15 days ago 5
Node.js Question

Get the list of rooms the client is currently in on disconnect event

I am trying to find the list of rooms a client is currently in on disconnect event (closes the browsers / reloading the page / internet connection was dropped).

I need it for the following reason: user has entered few rooms. Then other people has done the same. Then he closes a browser tab. And I want to notify all the people in the rooms he is in that he left.

So I need to do something inside of on 'disconnect' event.

io.sockets.on('connection', function(client){
client.on('disconnect', function(){


I already tried two approaches and found that both of them are wrong:

1) iterating through

for (room in client.adapter.rooms){'userDisconnected', UID);

This is wrong, because adapter rooms has all rooms. Not only the rooms my client is in.

2) Going through
. This returns a correct list of rooms the client is in, but no on the disconnect event. On disconnect this list is already empty

So how can I do it? I am using the latest at the time of writing: 1.1.0


This is not possible by default. Have a look at the source code of

There you have the method Socket.prototype.onclose which is executed before the socket.on('disconnect',..) callback. So all rooms are left before that.

 * Called upon closing. Called by `Client`.
 * @param {String} reason
 * @api private

Socket.prototype.onclose = function(reason){
  if (!this.connected) return this;
  debug('closing socket - reason %s', reason);
  this.connected = false;
  this.disconnected = true;
  delete this.nsp.connected[];
  this.emit('disconnect', reason);

A solution could be either to hack the socket.js library code or to overwrite this method and then call the original one. I tested it pretty quick at it seems to work:

socket.onclose = function(reason){
    //emit to rooms here
    //acceess socket.adapter.sids[] to get all rooms for the socket