Detect client disconnect

天涯浪子 提交于 2019-12-25 08:12:04

问题


I have a very simple socket.io connection. My server does the following:

io.sockets.on("connection", function (socket) {
    console.log("CONNECTED ON SERVER");                                 
    socket.emit("connected", "CONNECTED!");                                     
});

Indeed, the client gets the "CONNECTED!" message.

I need to be able to detect when a client disconnects and take some action. I've tried:

io.sockets.on("disconnect", function (socket) {                                 
    console.log("DISCONNECTED!");                                 
});

...but this does not log "DISCONNECTED!" on the server. However, CONNECTED ON SERVER from above does get logged.

I know that the socket can detect the disconnect because once I close the browser window, the server logs out:

info - transport end (socket end)
debug - set close timeout for client
debug - cleared close timeout for client
debug - cleared heartbeat interval for client
debug - discarding transport

This means that socket.io is able to detect that the client connection closed. How can I detect that it was closed?


回答1:


You have to set the event on each socket itself

You can see on their how to use page they set the disconnect event on the actual socket:

// note, io.listen(<port>) will create a http server for you
var io = require('socket.io').listen(80);

io.sockets.on('connection', function (socket) {
  io.sockets.emit('this', { will: 'be received by everyone'});

  socket.on('private message', function (from, msg) {
    console.log('I received a private message by ', from, ' saying ', msg);
  });

  socket.on('disconnect', function () {
    io.sockets.emit('user disconnected');
  });
});

If you take a look in the socket.io code (of at least v0.10.20) you will see that io.sockets is a SocketNamespace object (from namespace.js), and in that is the handlePacket function

the connection packet does

self.$emit('connection', socket);

Which will send the event to its own EventEmitter stuff.

Where as the disconnect packet is done this way:

socket.$emit('disconnect', packet.reason || 'packet');

So the disconnect event is never fired for the namespace object.

The current github code shows that they have moved the packet handling to their respective classes

connection emission in namespace.js Line 172

// fire user-set events
self.emit('connect', socket);
self.emit('connection', socket);

disconnect emission in socket.js Line 370

 ...
 this.disconnected = true;
 delete this.nsp.connected[this.id];
 this.emit('disconnect', reason);
};


来源:https://stackoverflow.com/questions/22315759/detect-client-disconnect

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