Socket.io socket property not found in disconnect event, node.js

╄→尐↘猪︶ㄣ 提交于 2020-01-16 18:36:52

问题


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


来源:https://stackoverflow.com/questions/15910213/socket-io-socket-property-not-found-in-disconnect-event-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!