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

杀马特。学长 韩版系。学妹 提交于 2019-11-30 20:09:50

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

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.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);
};

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[socket.id] to get all rooms for the socket
    console.log(socket.adapter.sids[socket.id]);
    Object.getPrototypeOf(this).onclose.call(this,reason);
}
André Morales

I know, it's an old question, but in the current version o socket.io there is a event that runs before disconnect that you can access the list of the rooms he 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

See also:

Server API documentation - 'disconnecting' event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!