socket.io get rooms which socket is currently in

2019-01-22 20:21发布

问题:

Is it possible to get rooms which socket is currently in, without calling

io.sockets.clients(roomName)

for every room name and looking for this socket in results

回答1:

From the Socket.IO Room doc:

io.sockets.manager.roomClients[socket.id]



回答2:

In socket.io version 1+ the syntax is:

socket.rooms


回答3:

socket.io 1.7.3+ ->

Object.keys( io.sockets.adapter.sids[socket.id] )
// returns [socket.id, room-x'] || [socket.id, 'room-1', 'room-2', ...]


回答4:

When using a non-default adapter, such as socket.io-redis, socket.rooms doesn't seem to do the trick. The way I managed to get the rooms for a specific client without looping was to use io.sockets.adapter.sids[socket.id], which returns the rooms as an object.

{ 'R-ZRgSf7h4wfPatcAAAC': true, ROOM: true, ROOM_2: true }

Note that this doesn't list sockets on other processes, though!

socket.io v1.3.7, socket.io-redis 1.0.0



回答5:

Version 1.7.3, socket.rooms contains socket.id, so remove it and get the list of rooms:

Object.keys(socket.rooms).filter(item => item!=socket.id);

In other version, you can print the socket and find the rooms.



回答6:

Being sure that socket is in only one room at a time, my solution was:

var currentRoom = Object.keys(io.sockets.adapter.sids[socket.id]).filter(item => item!=socket.id);


回答7:

You can save room in socket itself when it joins a room

// join room
socket.join(room);

// update socket's rooms
if (socket.rooms) {
    socket.rooms.push(room);
} else {
    socket.rooms = [room];
}

Later you can retrieve all rooms that the socket is in by simply

socket.rooms

From the Server API documentation:

socket.rooms (object)
A hash of strings identifying the rooms this client is in, indexed by room name.

https://socket.io/docs/server-api/#socket-rooms



回答8:

socket.io 1.7.3 +

var currentRoom = socket.rooms[Object.keys(socket.rooms)[0]];//returns name of room


回答9:

Version 2.0.3

io.sockets.sockets[yourSocketID].rooms

That equal with

socket.rooms


回答10:

Socket.io v2.1.1

So make sure you aren't accessing the sockets rooms in the disconnect event like I was, as they have already left the rooms by the time that event is triggered. If you want to do that try it in the disconnecting event - https://github.com/socketio/socket.io/pull/2332/files

Then you can use any of the following:

Object.keys(socket.adapter.rooms)
Object.keys(socket.adapter.sids)
Object.keys(socket.rooms)


回答11:

1.4.5 version => io.sockets.adapter.rooms[roomname].sockets