Sal*_*ali 8 node.js socket.io socket.io-1.0
我试图找到客户端当前处于断开连接事件的房间列表(关闭浏览器/重新加载页面/互联网连接已被删除).
我需要它的原因如下:用户进入了几个房间.然后其他人也这样做了.然后他关闭浏览器选项卡.我想通知他离开的房间里的所有人.
所以我需要在'disconnect'事件中做一些事情.
io.sockets.on('connection', function(client){
...
client.on('disconnect', function(){
});
});
Run Code Online (Sandbox Code Playgroud)
我已经尝试了两种方法,发现它们都是错误的:
1)迭代adapter.rooms.
for (room in client.adapter.rooms){
io.sockets.in(room).emit('userDisconnected', UID);
}
Run Code Online (Sandbox Code Playgroud)
这是错误的,因为适配器房间都有房间.不仅是我的客户所在的房间.
2)经历client.rooms.这将返回客户端所在房间的正确列表,但不会在disconnect事件中返回.断开连接时,此列表已空[].
那我该怎么办呢?我使用的是最新的socket.io在写作的时候:1.1.0
Der*_*erM 17
默认情况下这是不可能的.看看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);
};
Run Code Online (Sandbox Code Playgroud)
解决方案可能是破解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);
}
Run Code Online (Sandbox Code Playgroud)
And*_*les 10
我知道,这是一个老问题,但在当前版本的socket.io中有一个事件在断开连接之前运行,你可以访问他加入的房间列表.
client.on('disconnecting', function(){
Object.keys(socket.rooms).forEach(function(roomName){
console.log("Do something to room");
});
});
Run Code Online (Sandbox Code Playgroud)
https://github.com/socketio/socket.io/issues/1814
也可以看看:
| 归档时间: |
|
| 查看次数: |
2445 次 |
| 最近记录: |