获取客户端当前正在断开连接事件的房间列表

我试图find客户端当前正在断开连接事件的房间列表(closures浏览器/重新加载页面/互联网连接被丢弃)。

我需要它的原因如下:用户进入了几个房间。 其他人也这样做了。 然后他closures浏览器选项卡。 我想通知所有在他离开的房间里的人。

所以我需要在“断开连接”事件中做一些事情。

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

我已经尝试了两种方法,发现他们都是错的:

1)遍历adapter.rooms

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

这是错误的,因为适配器房间有所有房间。 不仅是我的客户所在的房间。

2)通过客户client.rooms 。 这将返回客户端所在房间的正确列表,但不会返回断开连接事件。 在断开连接时,这个列表已经是空的[]

那我该怎么做呢? 我在写这篇文章的时候使用了最新的socket.io:1.1.0

这是默认情况下不可能的。 看看socket.io的源代码。

socket.on('disconnect',..)callbacksocket.on('disconnect',..)之前执行的方法是socket.on('disconnect',..) 。 所以所有的房间都在此之前。

 /** * 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); }; 

一个解决scheme可能是破解socket.js库代码或覆盖此方法,然后调用原始的。 我testing它很快,似乎工作:

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

我知道,这是一个老问题,但在当前的版本中,socket.io中有一个事件在断开之前运行,您可以访问他join的房间列表。

 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