我正在尝试查找客户端当前在断开连接事件(关闭浏览器/重新加载页面/互联网连接断开)时所在的房间列表。
我需要它的原因如下:用户进入了几个房间。然后其他人也这样做了。然后他关闭浏览器选项卡。我想通知他所在房间的所有人他离开了。
所以我需要在“断开连接”事件中做一些事情。
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.prototype.onclose
方法,它在 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);
};
可能的解决方案是破解 socket.js 库代码或覆盖此方法然后调用原始方法。我很快就测试了它似乎有效:
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);
}
关于node.js - 在断开连接事件中获取客户端当前所在的房间列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25830415/