how to delete a room in socket.io

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)

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

Is that what you want ?

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

Solution 2

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

Solution 3

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

Solution 4

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)

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply