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

时间:2018-07-23 05:40:09

标签: javascript node.js socket.io

我要在用户由于不活动而断开连接时检测客户端。对我来说,使用disconnect()事件不起作用,因为它包含除不活动之外的其他形式的客户端断开连接。

我当前的代码:

var socket = io.connect();

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

2 个答案:

答案 0 :(得分:0)

这可能会对您有所帮助!

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.");
});

答案 1 :(得分:0)

在服务器端:

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

否则,客户端会收到一个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
});