Socket.io: how to clear the room ?

Created on 29 Aug 2017  ·  5Comments  ·  Source: socketio/socket.io

like io.to("chat").clear() , all socket in room "chat" will leave

Most helpful comment

i vote to add. room.kick() function where you can pass in a specific id, an array, or 'ALL" for removing everyone

All 5 comments

@wendux rooms are created and deleted automatically. That means when the room is empty, there are no more clients left on it, it will be deleted.
You can do this to remove all clients from a room:

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

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

});

https://socket.io/docs/server-api/#namespace-clients-callback

To complete @rllalloshi's answer, in a multi-server configuration you should use the removeLeave method of the adapter:

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

  socketIds.forEach(socketId => io.of('/').adapter.remoteLeave(socketId, 'chat'));

});

Reference

@wendux rooms are created and deleted automatically. That means when the room is empty, there are no more clients left on it, it will be deleted.
You can do this to remove all clients from a room:

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

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

});

https://socket.io/docs/server-api/#namespace-clients-callback

it did not work in socket.io 2.2.0

Why is there no simple call to remove all sockets from a room? It is a very common use case

i vote to add. room.kick() function where you can pass in a specific id, an array, or 'ALL" for removing everyone

Was this page helpful?
0 / 5 - 0 ratings

Related issues

thebinarypenguin picture thebinarypenguin  ·  4Comments

varHarrie picture varHarrie  ·  3Comments

adammw picture adammw  ·  4Comments

distracteddev picture distracteddev  ·  3Comments

gCurtisCT picture gCurtisCT  ·  4Comments