i'm trying to limit the number of users i can have in one room but i need to get the number of users currently in the room.
This is what my server.js looks like
socket.on("join-room", (roomId, userId) => {
var clients = io.sockets.adapter.rooms[roomId];
var numClients = typeof clients !== "undefined" ? clients.length : 0;
console.log(numClients);
if (numClients === undefined || numClients < 3) {
console.log('Joined room ' + roomId);
socket.join(roomId);
socket.to(roomId).emit("user-connected", userId);
io.to(roomId).emit('user-connected', userId);
} else {
console.log('room_full');
// socket.broadcast.to(userId).emit('room_full', 'for your eyes only');
}
});
This is the error i get in my logs
...
console.log(io.sockets.adapter.rooms[roomId].length)
2022-04-01T02:08:14.237151+00:00 app[web.1]: ^
2022-04-01T02:08:14.237151+00:00 app[web.1]:
2022-04-01T02:08:14.237152+00:00 app[web.1]: TypeError: Cannot read properties of undefined (reading 'length')
...
I have socketio@4.4.1
this code may help you
var activeUsers = new Set();
var clients = io.sockets.adapter.rooms[roomId];
activeUsers.add(clients);
console.log("active Users", activeUsers);
Output
active Users Set(1) { '62039f336226f0fdc7e90915' }