Socket.io socket property not found in disconnect

2019-09-14 17:04发布

问题:

I have a small but annoying problem that I can't find the solution for.

On the server side I have this:

...
socket.on('join', function (name) 
{
    console.log("Joining: "+name);
    socket.userName = sanitize(name);
}
socket.on('msg', function(m)
{
    console.log(socket.userName+" says: "+m);//This works
});

socket.on('disconnect', function(socket) 
{
    console.log(socket.userName+" has disconnected");//This does not work  
});
...

The issue is that the socket.userName is available in all my .on methods exept for socket.on('disconnect',...

I get undefined for the userName property.


Is this simply not possible to do? If this is not best pratcie, please let me know. I am farily new to node.js

回答1:

I don't think the disconnect event is passed an argument, so you're effectively clobbering your socket variable. Just use an empty argument list for its handler:

socket.on('disconnect', function() 
{
  console.log(socket.userName+" has disconnected");
});