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);
});
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);
});
}
You could keep track of all the sockets in a globally declared array in the beginning and then check the index of that array on the disconnect event. Something like this:
var allClients = [];
io.sockets.on('connection', function(socket) {
allClients.push(socket);
socket.on('disconnect', function() {
// this is your leaving Socket object
var index = allClients.indexOf(socket);
var leaving_socket = allClients[index];
// this is the way to get the rooms in 1.3.7
console.log(leaving_socket.rooms);
}
}
You can check out the documentation here
EDIT
The leaving_socket.rooms
is, of course, an array and not a string, since a single socket can be in many rooms at one time. That means you are going to have to loop through that array and find the one you are looking for. A socket is also always in a room that has the same name as the id of the socket.