简体   繁体   English

Node.js + Socket.io:当用户由于不活动而断开连接时,检测客户端

[英]Node.js + Socket.io: Detect client-side when user has disconnected due to inactivity

I want to detect client-side when a user has disconnected due to INACTIVITY . 当用户由于INACTIVITY断开连接时,我想检测客户端。 For me, using a disconnect() event doesn't work because it encompasses other forms of a client disconnecting besides inactivity. 对我来说,使用Disconnect()事件不起作用,因为它包含除不活动状态以外的其他形式的客户端断开连接。

My current code: 我当前的代码:

var socket = io.connect();

socket.on("disconnect", () => {
    console.log("You have been disconnected from the match.");
});

This might help you! 这可能对您有帮助!

 var socket = io.connect(); socket.on("disconnect", () => { //it emits a logoff event socket.emit("logoff", { reason: "Disconnected due to inactivity" }); console.log("You have been disconnected from the match."); }); 

On your server side: 在服务器端:

io.on('connection', function(socket){
  socket.on('disconnect', function(){
    console.log('user disconnected'); // client has been disconnected, client maybe has many connections.
  });
});

Orther way, Client side takes a http request to noti to server that it has been disconnected. 否则,客户端会收到一个http请求以通知服务器已断开连接。

var socket = io.connect();

socket.on("disconnect", () => {
    console.log("You have been disconnected from the match.");
    $.post('http://serverdomain/socket/' + socket.id + '/disconnected') // Just make a http request,
    // example by jQuery
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM