socket.io get rooms which socket is currently in

2019-01-22 20:36发布

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

11条回答
不美不萌又怎样
2楼-- · 2019-01-22 20:42

socket.io 1.7.3+ ->

Object.keys( io.sockets.adapter.sids[socket.id] )
// returns [socket.id, room-x'] || [socket.id, 'room-1', 'room-2', ...]
查看更多
萌系小妹纸
3楼-- · 2019-01-22 20:48

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);
查看更多
虎瘦雄心在
4楼-- · 2019-01-22 20:52

socket.io 1.7.3 +

var currentRoom = socket.rooms[Object.keys(socket.rooms)[0]];//returns name of room
查看更多
干净又极端
5楼-- · 2019-01-22 20:55

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楼-- · 2019-01-22 20:56

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

查看更多
7楼-- · 2019-01-22 20:57

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

查看更多
登录 后发表回答