Disconnect all room users when "Host" disconnects in Socket.IO

I currently have a creator for a room labeled "Host". I need to set it up so that if the "Host" clicks the "Close Room" link, it will disconnect all users from that room id.

How can I grab all users from socket.manager.roomClients

or some of these roles, skip all of them and start some type socket.leave( room_id )

if the "host" room_id matches the key in the socket manager?

Thanks for your understanding or help. Let me know if I need to clarify anything.


source to share

3 answers

There is no mechanism for this in socket.io, but it is not very difficult to implement. You just loop over every socket in the room and call the disconnect method. Ideally this would be an io.sockets level method, but you need to know the namespace the socket is using, so I added a socket level prototype to get everyone out of the room. Take a look at the following:

var sio = require('socket.io');
var io = sio.listen(app);

sio.Socket.prototype.disconnectRoom = function (name) {
    var nsp = this.namespace.name
    , name = (nsp + '/') + name;

    var users = this.manager.rooms[name];

    for(var i = 0; i < users.length; i++) {

    return this;


You can use it as shown below.

socket.on('hostdisconnect', function() {


A word of warning, if you're going to use something like this, it's important to know that it uses internal data structures that may or may not be in the next version of socket.io. It is possible for an upgrade from socket.io to break this functionality.



After much fighting trying to do it via socket.io, I figured out a way to get the room to kill via Node.JS / Express

app.get('/disconnect', function(req, res){
  console.log("Disconnecting Room " + req.session.room_id);
    if (err){
      console.log('Error destroying room... ' + err);
    } else{




The latest update in socket.io is the leave () method as a companion for connection ().

For example,



Maybe this will help you in your scenario.



All Articles