socket.io get rooms which socket is currently in

前端 未结 12 1207
臣服心动
臣服心动 2020-12-14 08:40

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

io.sockets.clients(roomName)

for every room name and looking for

12条回答
  •  我在风中等你
    2020-12-14 08:50

    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

提交回复
热议问题