简体   繁体   中英

Check for Client Reconnection Before Disconnect Triggers

So I'm trying to have a real-time display of my online players, and it's working great thus far except for one issue. When my app listens for the disconnect, it appears that a page refresh triggers this function and said player is logged out.

app.io.route("disconnect", function(req,res) {
    db.query("UPDATE player_data SET online=0 WHERE id="+mysql.escape(req.session.user));
    req.io.broadcast("event", {msg:req.session.username+" has logged out!"});
    app.io.broadcast("reloadXY");
    req.session.destroy();
});

Why is a page refresh triggering this function? (I know it's this function because the only other way a player is logged out is via the logout link) How can I have it ignore page refreshes and only catch disconnections like closing the browser?

Edit: how can I "ping" for the reconnect event so that I can check if the page was reloaded versus closed? A reload will have an instant re-connection, so I just need to check for said reconnection. I just don't know how!

Thanks to Zirak (and Tim Cooper, although at the time I had no idea what he meant), I was able to solve this issue. He suggested I store a disconnection timeout inside my session, and when there is a re-connection (instant because of page-reloads), simply clear the timeout before it auto-logs out the player.

app.io.route("stopDisconnection", function(req) {
    if (req.session) {
        clearTimeout(req.session.disconnection);
        console.log("Timeout cleared");
    }
});

app.io.route("disconnect", function(req) {
    req.session.disconnection = setTimeout(function() {
        console.log("User timed out!");
        db.query("UPDATE player_data SET online=0 WHERE id="+mysql.escape(req.session.user));
        app.io.broadcast("event", {msg:req.session.username+" has logged out!"});
        app.io.broadcast("reloadXY");
        req.session.destroy();
    },5000);
});

And simply call io.emit("stopDisconnection") on index.html

And with that, you can successfully trigger a disconnect function without having to worry about a page refresh also trigger the event.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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