1

I want to get number of participants in a room while using socket.io

This is what I am trying to do

io.on("connection", function (socket) {
  console.log("User Connected " + socket.id);

  io.on("join", function (roomName) {
    var numClients = io.sockets.adapter.rooms[roomName].length;
    if (numClients == 0) {
      socket.join(roomName);
    } else if (numClients == 1) {
      socket.join(roomName);
    } else {
      console.log("More than 2 users.");
    }
  });
});
ThejasSatheesh
  • 163
  • 2
  • 6

2 Answers2

4

For version 3.0 and Above you have to use the get function with the rooms object. The use .size() to get the number of clients.

So it would look something like this

io.sockets.adapter.rooms.get(roomName).size
1

The previous answer only works after at least one user has joined/created the room, before that i'll given an error since the room won't exist.

I have posted the Maps in io.sockets.adapter.rooms in another question.

Therefore, what worked for me ("socket.io": "^4.1.2"), was to ask for the number of clients in the room using this:

let clientsInRoom = 0;
if (io.sockets.adapter.rooms.has(room)) clientsInRoom = io.sockets.adapter.rooms.get(room).size
Julio Spinelli
  • 587
  • 3
  • 16