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

Problem

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

Solution

There doesn't appear to be a mechanism for this in socket.io, 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('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 

You can use it as shown below.

socket.on('hostdisconnect', function() {
    socket.disconnectRoom('roomName');
});

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 socket.io. It's possible for an update from socket.io to break this functionality.

Solution courtesy of: Timothy Strimple

Discussion

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

×