Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

socket.id of disconnecting client?

Tags:

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);     }); }); 
like image 292
Nyxynyx Avatar asked Nov 27 '11 15:11

Nyxynyx


People also ask

How do I find my 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 do I remove Socket.IO client side?

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(); };


1 Answers

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);     }); }); 
like image 170
Felix Loether Avatar answered Sep 22 '22 23:09

Felix Loether