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

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

问题描述

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

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天全站免登陆