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);
});
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');
});
});
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);
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With