Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Disconnect All Users of Room when "Host" Disconnects in Socket.IO

Disconnect All Users of Room when "Host" Disconnects in Socket.IO


Currently I have the originator of a room marked as the "Host". I need to set it so that if the "Host" clicks a "Close Room" link, it will Disconnect all over users from that room id.

How can I grab all users from socket.manager.roomClients or something of the sorts, loop through them all and run some type of socket.leave( room_id ) if the "Host's" room_id matches the key in the socket manager?

Thanks for any insight or help. Let me know if I need to clarify anything.

Problem courtesy of: LostInQuery


There doesn't appear to be a mechanism for this in, but it's not terribly difficult to implement it yourself. You just iterate over each socket in the room and call the disconnect method. This would ideally be a io.sockets level method, but you've got to know the namespace that the socket is using, so I added a prototype at the socket level to boot everyone out of a room. Take a look at the following:

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

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

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

    for(var i = 0; i 

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 be aware it uses internal data structures which may or may not be around in the next version of It's possible for an update from to break this functionality.

Solution courtesy of: Timothy Strimple


View additional discussion.

This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Disconnect All Users of Room when "Host" Disconnects in Socket.IO


Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription