Is it possible to get the socket.id
of the client that has disconnected? The following code gives me undefined
for socket.id
Node.js Code
io.sockets.on('connection', function() { socket.on('disconnect', function(socket) { console.log(socket.id); }); });
socket.id can be obtained after 'connect' event. Note, the socket.id on the server is not made available to the client, so if you want the id from the server, then you can send it to the client yourself in a message.
How can I close the connection on the client side or check if there is already a open connection? window. onbeforeunload = function(e) { socket. disconnect(); };
The callback function that io.sockets.on
takes as its second argument is supposed to take one argument: the socket. Yours doesn't, so the socket on the second line's socket.on
is undefined.
And the callback for socket.on
isn't given any arguments, so the socket
in that function is also undefined.
The code should work if you move the socket parameter from the second function declaration to the first:
io.sockets.on('connection', function (socket) { socket.on('disconnect', function () { console.log(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