Get a list of rooms in which the client is in a disconnected state

I am trying to find a list of rooms in which the client is currently in a disconnected event (closes browsers / reloads the page / Internet connection has been deleted).

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

So I need to do something inside the "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) iterate through adapter.rooms .

 for (room in client.adapter.rooms){ io.sockets.in(room).emit('userDisconnected', UID); } 

This is wrong because the rooms for the adapters have all the rooms. Not just my client numbers.

2) Transition through client.rooms . This returns the correct list of rooms the client is in, but not in the disconnect event. When disabled, this list is already empty [] .

So how can I do this? I am using the latest version of socket.io at the time of writing: 1.1.0

+7
source share
2 answers

By default this is not possible. Check out the source code for socket.io.

There you have the Socket.prototype.onclose method, which is executed before the socket.on('disconnect',..) . Thus, all rooms remain 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.leaveAll(); this.nsp.remove(this); this.client.remove(this); this.connected = false; this.disconnected = true; delete this.nsp.connected[this.id]; this.emit('disconnect', reason); }; 

The solution can either hack socket.js library code, or overwrite this method, and then call the original one. I tested this pretty quickly, it looks like it works:

 socket.onclose = function(reason){ //emit to rooms here //acceess socket.adapter.sids[socket.id] to get all rooms for the socket console.log(socket.adapter.sids[socket.id]); Object.getPrototypeOf(this).onclose.call(this,reason); } 
+16
source share

I know this is an old question, but in the current version of o socket.io there is an event that runs before disconnecting, that you can access the list of rooms to which it has joined.

 client.on('disconnecting', function(){ Object.keys(socket.rooms).forEach(function(roomName){ console.log("Do something to room"); }); }); 

https://github.com/socketio/socket.io/issues/1814

+4
source share

All Articles