Question

I want to statically remove all users from a room, effectively deleting that room. The idea is that another room with the same name may be created again in the future, but I want it created empty (without the listeners from the previous room).

I'm not interested in managing the room status myself but rather curious as if I can leverage socket.io internals to do this. Is this possible? (see also this question)

Was it helpful?

Solution

Is that what you want ?

io.sockets.clients(someRoom).forEach(function(s){
    s.leave(someRoom);
});

OTHER TIPS

For an up-to-date answer to this question, everyone who wants to remove a room can make use of Namespace.clients(cb). The cb callback will receive an error object as the first argument (null if no error) and a list of socket IDs as the second argument.

It should work fine with socket.io v2.1.0, not sure which version is the earliest compatible one.

io.of('/').in('chat').clients((error, socketIds) => {
  if (error) throw error;

  socketIds.forEach(socketId => io.sockets.sockets[socketId].leave('chat'));

});

@See https://github.com/socketio/socket.io/issues/3042
@See https://socket.io/docs/server-api/#namespace-clients-callback

if you are using socket io v4 or greater you can use this:

io.in("room1").socketsLeave("room1");

//all the clients in room1 will leave romm1
//hence deleting the room automatically
//as there are no more active users in it

Also, it's worth mentioning that...

Upon disconnection, sockets leave all the channels they were part of automatically, and no special teardown is needed on your part.

https://socket.io/docs/rooms-and-namespaces/ (Disconnection)

To add onto ROCK ON's answer for for version 4.X. If you need to do more than just leave the room, you can do:

const sockets = await io.in(room).fetchSockets();
sockets.forEach(s => {
  // Do stuff
  s.emit('host disconnected', room);
  s.leave(room);
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top