Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send message to room clients when a client disconnects

I want the server to send a message to all room clients when one of them disconnects.

Something like this:

socket.on('disconnect', function() {
    server.sockets.in(room).emit('bye');
});

But...

  • How do I know which room to broadcast?
  • What if the client has joined to multiple rooms?
like image 711
Peter Avatar asked Dec 03 '12 12:12

Peter


People also ask

How do I send a message to a specific user in socket?

You can try the code below:io.to(socket.id). emit("event", data); whenever a user joined to the server, socket details will be generated including ID. This is the ID really helps to send a message to particular people.

How do I disconnect a client from a server?

Click Server, Server Manager. The Clients Messaging Center dialog box opens. Select Disconnect Clients. Specify a Minutes interval to determine when the clients will be disconnected.

Does socket.io reconnect after disconnect?

Socket disconnects automatically, reconnects, and disconnects again and form a loop. #918.


1 Answers

After inspecting the sockets object, I came up with this solution:

socket.on('disconnect', function() {
    var rooms = io.sockets.manager.roomClients[socket.id];
    for (var room in rooms) {
        if (room.length > 0) { // if not the global room ''
            room = room.substr(1); // remove leading '/'
            console.log('user exits: '+room);
            server.sockets.in(room).emit('bye');
        }
    }
});
like image 147
Peter Avatar answered Oct 04 '22 22:10

Peter