问题描述:

I code a chat room using socket.io >1.0

In my chat room application I try to understand who is just disconnected. To do that I need to access socket's id.

After the disconnect event is triggered,

 socket.on('disconnect', function(socket){

//need to learn socket's id here

}

I cannot check who just left. I tried socket.id but that gave an error. I think the socket object is deleted because I cannot reach any part of it.

And I don't want to store all socket ids and loop through all of them when one is left.

Then I tried saving the socket's id in session using session middleware, yet either they attach the data to socket object so using it is meaningless(all data is gone when disconnected) or they use the REST calls but I don't receive any REST call when someone(a socket) leaves the chatroom.

Thanks a lot

网友答案:

Try this:

io.sockets.on('connection', function(socket){
          console.log("Connected Socket = " + socket.id)
          socket.on('disconnect', function(){
                 console.log("Disconnected Socket = " + socket.id);
          }
 } 

Let me know if that works.

EDIT1: Essentially what you were doing was wrong, logically. The callback function associated to a connection was executed after somebody connected, and therefore lost, or, dereferenced within the event loop.

My answer will keep your callback referenced within the event loop, and if that connection is referenced again, you'd be able to identify what thread, or connection, called that method.

相关阅读:
Top