简体   繁体   English

在socket.io中获得套接字的空间

[英]get room of a socket in socket.io

How do I retrieve the rooms a socket is a member of? 如何检索套接字所属的房间? I'm using socket.io version 1.4 我正在使用1.4版本的socket.io

I tried with this.socket.adapter.rooms but I received this error in the chrome console: Cannot read property 'rooms' of undefined 我尝试使用this.socket.adapter.rooms但在Chrome控制台中收到此错误: Cannot read property 'rooms' of undefined

In my client code I have this method: 在我的客户代码中,我有以下方法:

send(msg) {
        if(msg != ''){
            var clientInfo = [];
            clientInfo.push(msg);
            clientInfo.push(socket.id);
            clientInfo.push(this.socket.adapter.rooms);
            socket.emit('message', clientInfo);
        }
    }

On my server side: 在我的服务器端:

socket.on('message', function(clientInfo){
        var clientmessage = clientInfo[0];
        var clientid = clientInfo[1];
        var clientroom = clientInfo[2];
        io.to(clientroom).emit('messageSent', clientmessage);
    });

Server side, you can get a list of rooms a socket is in with: 服务器端,您可以获取套接字所在的房间的列表:

socket.rooms

Client side, a socket does not know what rooms it is in. The whole concept of rooms is a server-side concept and all the data structures are maintained there. 在客户端,套接字不知道它所在的房间。房间的整个概念是服务器端的概念,所有数据结构都保存在那里。 If a client wanted to know what rooms it was in, it would either have to keep track of what rooms it requested to be a member of or it would have to ask the server what rooms it is in. 如果客户想知道它所在的房间,要么要么跟踪它要求成为哪个房间的成员,要么就必须询问服务器它所在的房间。

There is one oddity about the server-side socket.rooms structure. 服务器端socket.rooms结构有一个怪异之处。 It is apparently not updated real-time. 它显然不是实时更新的。 If you do socket.join("someRoom") and then immediately look at socket.rooms , you will not see the someRoom name listed. 如果执行socket.join("someRoom")然后立即查看socket.rooms ,则不会看到列出的someRoom名称。 But, if you look on process.nextTick() or on setTimeout() , you will see it in socket.rooms . 但是,如果您查看process.nextTick()setTimeout() ,则会在socket.rooms看到它。 I haven't delved into the socket.io source code to figure out why that is the way it is, but apparently something is only being updated asynchronously. 我没有深入研究socket.io源代码来弄清楚为什么会这样,但是显然有些东西只是异步更新的。

            Object.keys(socket.rooms).forEach(function(room, idx) {
                if(idx!=0){
                    console.log(idx,"-->",room)
                }
             });

By the above code you can identify all the rooms the socket have joined. 通过上面的代码,您可以确定套接字已加入的所有房间。 You can skip the first room which is in index 0 as it is the default room a socket will connect on connection. 您可以跳过索引为0的第一个房间,因为这是套接字在连接时将连接的默认房间。

Tested this with SocketIO 1.7 and works well. 在SocketIO 1.7上进行了测试,效果很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM