node.js - Socket.io auto disconnect after 2 hours of inactivity not working -
i'd disconnect users socket.io after 2 hours of inactivity , give them prompt / reconnect button.
firstly, have set auto reconnect false , variable forcedc:
var socket = io.connect('https://coinchat.org:443',{secure: true, reconnect: false}); var forcedc = false;
next, have time out inactivity reset when moves mouse:
$("body").mousemove(function(e){ cleartimeout(dctimeout); dctimeout = settimeout(function(){ if(!forcedc){ forcedc = true; socket.disconnect(); $("#dcmodal").modal('show'); } }, 1000 * 60 * 60 * 2); });
basically, forcedc means user disconnected due inactivity , browser should not refresh page try , reconnect. if forcedc false, means user disconnected due network issues / server restarts, , browser should refresh page reconnect.
now, when socket disconnected:
socket.on("disconnect", function(data){ if(!forcedc){ settimeout(function(){document.location.reload(true)}, 1000 + math.random()*12750); } });
the page should refresh if forcedc false. however, page refreshes if user has been "disconnected" due inactivity (i know forcedc = true has been executed, see disconnected modal).
what doing wrong?
i believe dctimeout never gets cleared via 'cleartimeout(dctimeout);". hence, dctimeout gets executed , forcedc becomes true.
possible solution: declare dctimeout global variable along forcedc. here's jsfiddle link test code reference.
function communication() { var socket = io.connect('http://localhost:8080',{reconnect: false}); socket.on('connect', function () { var forcedc = false; var dctimeout = null; console.log("connected server!"); socket.on('news', function (data) { console.log(data); }); socket.on("disconnect", function(data){ console.log("disconnected..") if(!forcedc){ console.log("forcedc false , socket has been disconnected"); settimeout(function(){ console.log("reloading document in 2 seconds"); //document.location.reload(true) }, 2000); } }); document.onmousemove = function(e){ console.log("mouse movement detected"); cleartimeout(dctimeout); dctimeout = settimeout(function(){ if(!forcedc){ forcedc = true; console.log("disconnecting...setting true"); socket.disconnect(); //$("#dcmodal").modal('show'); console.log("disconnected! want reconnect?"); } }, 5000 * 1); } }); }
Comments
Post a Comment