获取客户端当前在断开连接事件中的房间列表 [英] Get the list of rooms the client is currently in on disconnect event

查看:22
本文介绍了获取客户端当前在断开连接事件中的房间列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在断开连接事件(关闭浏览器/重新加载页面/断开互联网连接)时查找客户端当前所在的房间列表.

I am trying to find the list of rooms a client is currently in on disconnect event (closes the browsers / reloading the page / internet connection was dropped).

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

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

所以我需要在 'disconnect' 事件内部做一些事情.

So I need to do something inside of on '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) 遍历 adapter.rooms.

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

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

This is wrong, because adapter rooms has all rooms. Not only the rooms my client is in.

2) 浏览 client.rooms.这将返回客户端所在房间的正确列表,但不会在断开连接事件中返回.断开连接时,此列表已为空 [].

2) Going through client.rooms. This returns a correct list of rooms the client is in, but no on the disconnect event. On disconnect this list is already empty [].

那我该怎么办呢?在撰写本文时,我使用的是最新的 socket.io:1.1.0

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

推荐答案

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

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

您有方法 Socket.prototype.onclose,它在 socket.on('disconnect',..) 回调之前执行.所以在此之前所有房间都被留下了.

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

解决方案可以是破解 socket.js 库代码或覆盖此方法然后调用原始方法.我很快就测试了它似乎可以工作:

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

这篇关于获取客户端当前在断开连接事件中的房间列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆