0

I am looking for a way to check the amount of users in a room to make sure that, if there are already 2 players in it, I can block the player from joining. However, the code and examples I have found online has been out-of-date. Currently, I am using socket.io 3.0.1.

io.on("connection", socket => {
  socket.on("join", (room, username) => {
    var users = io.sockets.clients(room)
    if (typeof users === 'undefined') {
      users = []
    }
    console.log(users.length);

    if (users.length <= 1) {
      socket.join(room);
      io.in(room).emit("join", username);
      socket.emit("lobbyJoined");
      users = io.sockets.adapter.rooms[room]
      console.log("users in " + room + ": " + users);
    } else {
      socket.emit("lobbyFull");
    }
  });
});

io.sockets.clients(room) which is recommended in other posts, throws an error: TypeError: io.sockets.clients is not a function, and io.sockets.adapter.rooms[room] returns 'undefined', even if there is a user connected to that room.

Any help would be greatly appreciated.

  • Possible duplicate: https://stackoverflow.com/questions/31468473/how-to-get-socket-io-number-of-clients-in-room – holtc Nov 21 '20 at 09:15
  • Have a look here https://stackoverflow.com/questions/6563885/socket-io-how-do-i-get-a-list-of-connected-sockets-clients – Ukiyo Nov 21 '20 at 09:16
  • @holtc @Ashwin I had tried those, though none of them appear to work. They all either give an error, or return 'undefined'. I thought that might have been caused by the fact that there were no users in the room, so the room didn't actually exist. However, after I let one user in, it still returned 'undefined'. I have tried several methods that should return a list of sockets connected to a room: `io.sockets.adapter.rooms[room]`, `io.sockets.clients(room)` – SinglePaper Nov 21 '20 at 09:32
  • can you post your code? – holtc Nov 21 '20 at 09:33
  • @holtc I have added the relevant code to the original post. – SinglePaper Nov 21 '20 at 09:41
  • `// all sockets in the "chat" namespace and in the "general" room io.of("/chat").in("general").clients((error, clients) => { console.log(clients); });` h/t https://socket.io/docs/v3/migrating-from-2-x-to-3-0/#Namespace-clients-is-renamed-to-Namespace-allSockets-and-now-returns-a-Promise – holtc Nov 21 '20 at 09:58

1 Answers1

1

You are getting undefined in io.sockets.adapter.rooms[room] even if there is a user connected to that room because

The rooms property contains the list of rooms the Socket is currently in. It was an object, it is now an ES6 Set.

//this is an ES6 Set of all client ids in the room

Try this

users = io.sockets.adapter.rooms.get('Room Name');
Sachin
  • 1,206
  • 12
  • 13