How to handle socket.io disconnect by client by leaving page?

喜欢而已 提交于 2020-01-24 12:53:27

问题


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.



来源:https://stackoverflow.com/questions/27696675/how-to-handle-socket-io-disconnect-by-client-by-leaving-page

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