除了来自客户端的心跳之外,Socket.io检查不活动

我有一个使用nodejssocket.io具有聊天function的PHP应用程序。 我现在需要做的是如果用户hibernate超过15分钟,则将用户注销。

会话在PHP应用程序和Nodejs服务器之间共享。 因此, nodejs服务器知道用户上次login的时间或者上次活动的时间。

我正在考虑向socket.io客户端发送一个logoff命令,如果我能够区分心跳和来自客户端的消息,这将非常容易。

由于PHP应用程序只会了解用户在页面重新载入或导航时的活动,因此用户仍然可以在hibernate状态下进行聊天,而PHP应用程序不会知道用户是否正在聊天。 所以从会话中检查用户的最后一个活动将不起作用。

所以这里主要的问题是,我可以识别一个只发送超过15分钟(不发射)心跳的客户吗?

根据聊天活动注销最简单的方法是每次用户聊天时都有一个简单的计时器。 像这样的东西:

 io.sockets.on('connection', function(socket) { // ... var logoffTimer; socket.on('chat', function() { // clear the timer on activity // should also update activity timestamp in session clearTimeout(logoffTimer); // set a timer that will log off the user after 15 minutes logoffTimer = setTimeout(function(){ // add log off logic here // you can also check session activity here // and perhaps emit a logoff event to the client as mentioned socket.emit("logoff", { reason: "Logged off due to inactivity" }); }, 60 * 15); }); });