socket.io get rooms which socket is currently in

前端 未结 12 1191
臣服心动
臣服心动 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:54

    Update: Socket.io 3.0 Released


    With 3.x Socket.rooms is Set now, which means that values in the rooms may only occur once.

    Structure example: Set(4) {"", "room1", "room2", "room3"}

    io.on("connect", (socket) => {
      console.log(socket.rooms); // Set {  }
      socket.join("room1");
      console.log(socket.rooms); // Set { , "room1" }
    });
    

    To check for specific room:

    socket.rooms.has("room1"); // true
    

    More about Set and available methods: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set

    Migration Docs: https://socket.io/docs/migrating-from-2-x-to-3-0/

提交回复
热议问题