Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket.io check for inactivity apart from heartbeat from client

I have a PHP application that has a chat functionality using nodejs and socket.io. What I now need to do is to log the user out if the user is dormant for more than 15 minutes.

The sessions are shared between the PHP application and Nodejs server. So nodejs server knows when a user last logged in or when his/her last activity was.

I am thinking of sending a logoff command to the socket.io client, and it would be really easy if I could distinguish between the heartbeat and a message from a client.

As the PHP application would only know about the activity of a user on a page reload or navigation, the user could still be chatting while he is dormant and PHP application won't know if the user is chatting. So checking the last activity of a user from session won't work.

So main question here is, can I identify a client which has only been sending heartbeat for more than 15 minutes (no emits) ?

like image 336
Broncha Avatar asked Jan 03 '13 10:01

Broncha


1 Answers

The easiest way to log off based on chat activity is to have a simple timer that is reset every time the user is chatting. Something like this:

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);
    });
});
like image 131
mekwall Avatar answered Sep 28 '22 00:09

mekwall