How to handle socket.io disconnect by client by le

2019-07-18 01:53发布

问题:

I have a socket.io application with node.js and was wondering what possibilities exist to respond to a client simply closing their browser window. Is there anyway to know that this has been done? What kinda of signal can been sent to the server?

If I don't have a way of doing telling if a particular client has disconnected what else can I do?

回答1:

I have a socket.io application with node.js and was wondering what possibilities exist to respond to a client simply closing their browser window. Is there anyway to know that this has been done? What kinda of signal can been sent to the server?

Your socket on the node.js side will receive a "disconnect" event when the browser closes the connection, which you can then react to.



回答2:

When a client closes their browser window, socket.io fires a special 'disconnect' event.

Assuming you've required socket.io in your node server file

var io = require('socket.io');

then you can listen for the 'disconnect' event fired by each socket:

io.on('connection', function(socket){
  console.log('a user connected');
  socket.on('disconnect', function(){
    console.log('user disconnected');
  });
});

Note - socket here is given by:

io.on('connection', function(socket){
  console.log('a user connected');
});

source: http://socket.io/get-started/chat/



回答3:

You want to fire a message over your socket in an unload trigger.

<body onunload="sendBrowserClosedMessageToServer()">

Or whatever you call your hook.