IamTester
IamTester

Reputation: 31

Socket.io on socket disconnect

I have this scenario with socket.io:

A socket connects and joins a room and he is the master. Other sockets join his room. When master disconnects I want to kick all other sockets from this room.

I thought of this:

socket.on('disconnect', function(data){
    // if socket's id == room  he is the master and kick other sockets from this 
    // room and join them to a room of their own identified by their ids.       
});

I want to do this without too much logic and for loops to stall the application. Is it possible to something like io.sockets.leave(socket.room)?

Upvotes: 2

Views: 6775

Answers (2)

Erel Segal-Halevi
Erel Segal-Halevi

Reputation: 36745

alessioalex's answer returns an error because it tries to call "leave" on an array of sockets. This is a working solution:

io.sockets.clients(socket.room).forEach(function(listener) {
    listener.leave(socket.room);
});

Upvotes: 5

alessioalex
alessioalex

Reputation: 63663

I am not 100% sure, but after reading Socket.IO's documentation on github I think this should work:

io.sockets.in(socket.room).leave(socket.room);

Upvotes: 3

Related Questions