How to handle socket.io disconnect by client by leaving page?
Solution 1
I have a socket.io application with node.js and was wondering what possibilities exist to respond to a client simply closing their browser window. Is there anyway to know that this has been done? What kinda of signal can been sent to the server?
Your socket on the node.js side will receive a "disconnect" event when the browser closes the connection, which you can then react to.
Solution 2
When a client closes their browser window, socket.io fires a special 'disconnect' event.
Assuming you've required socket.io in your node server file
var io = require('socket.io');
then you can listen for the 'disconnect' event fired by each socket:
io.on('connection', function(socket){
console.log('a user connected');
socket.on('disconnect', function(){
console.log('user disconnected');
});
});
Note - socket here is given by:
io.on('connection', function(socket){
console.log('a user connected');
});
source: http://socket.io/get-started/chat/
Solution 3
You want to fire a message over your socket in an unload trigger.
<body onunload="sendBrowserClosedMessageToServer()">
Or whatever you call your hook.
Bren
Updated on June 05, 2022Comments
-
Bren almost 2 years
I have a
socket.io application
withnode.js
and was wondering what possibilities exist to respond to a client simply closing their browser window. Is there anyway to know that this has been done? What kinda of signal can been sent to the server?If I don't have a way of doing telling if a particular client has disconnected what else can I do?