Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current room of socket on disconnect?

On socket.io 1.3.7, how to get the room of the socket on disconnect event?

socket.on('disconnect', function() {
    var currentRoom = ???
    socket.broadcast.in(currentRoom).emit('user:left', socket.id);
});
like image 878
Tib Avatar asked Dec 04 '15 16:12

Tib


2 Answers

The rooms are already left upon the 'disconnect' event, use the 'disconnecting' event which will be emitted before the 'disconnect' event takes place whe the rooms are still accesible.

It works like this:

socket.on('disconnecting', function(){
    var self = this;
    var rooms = Object.keys(self.rooms);

    rooms.forEach(function(room){
        self.to(room).emit('user left', self.id + 'left');
    });
});
like image 78
Skoempie Avatar answered Oct 05 '22 02:10

Skoempie


I solved my problem by setting currentRoomId variable on connection, so I have access to it in disconnect.

io.sockets.on('connection', function(socket) {
    var currentRoomId;
    socket.on('join', function(roomId) {
      socket.join(roomId);
      currentRoomId = roomId;
    });

   socket.on('disconnect', function() {
     socket.broadcast.in(currentRoomId).emit('user:left', socket.id);
   });
}
like image 32
Tib Avatar answered Oct 05 '22 04:10

Tib