Detect Client Disconnect
I have a very simple socket.io connection. My server does the following: io.sockets.on('connection', function (socket) { console.log('CONNECTED ON SERVER');
Solution 1:
You have to set the event on each socket itself
You can see on their how to use page they set the disconnect event on the actual socket:
// note, io.listen(<port>) will create a http server for you
var io = require('socket.io').listen(80);
io.sockets.on('connection', function(socket) {
io.sockets.emit('this', { will: 'be received by everyone'});
socket.on('private message', function(from, msg) {
console.log('I received a private message by ', from, ' saying ', msg);
});
socket.on('disconnect', function() {
io.sockets.emit('user disconnected');
});
});
If you take a look in the socket.io code (of at least v0.10.20) you will see that io.sockets
is a SocketNamespace object (from namespace.js), and in that is the handlePacket
function
the connection packet does
self.$emit('connection', socket);
Which will send the event to its own EventEmitter stuff.
Where as the disconnect packet is done this way:
socket.$emit('disconnect', packet.reason || 'packet');
So the disconnect event is never fired for the namespace object.
The current github code shows that they have moved the packet handling to their respective classes
connection emission in namespace.js Line 172
// fire user-set eventsself.emit('connect', socket);
self.emit('connection', socket);
disconnect emission in socket.js Line 370
...
this.disconnected = true;
delete this.nsp.connected[this.id];
this.emit('disconnect', reason);
};
Post a Comment for "Detect Client Disconnect"