一尘不染

处理浏览器重载socket.io

node.js

socket.io中有一种方法可以在断开连接的事件中创建超时,然后检查用户是否已重新连接?

这个想法是仅在超时后未重新连接用户时才发出数据/将用户状态保存在数据库中

编辑 :@Are Wojciechowski回答之后,我已经完成了多个标签页和F5洪水处理程序

https://gist.github.com/foohey/7696811


阅读 249

收藏
2020-07-07

共1个答案

一尘不染

有一个socket.on('disconnect', function () { ... });。所以你可以做

socket.on('disconnect', function () {
    setTimeout(function () {
         //do something
    }, 10000);
});

编辑1:

我明白了 因此,也许您应该执行以下操作:

客户:

//right after connection
socket.emit('register', localstorage.getItem('gameUniqueId'));

//somewhere, when game starts
var randomlyGeneratedUID = Math.random().toString(36).substring(3,16) + +new Date;
localStorage.setItem('gameUniqueId', randomlyGeneratedUID);

服务器:

io.sockets.on('connection', function (socket) {
    var player = null;

    socket.on('register', function (data) {
        if (data !== null) {
            //there was something in localstorage
            if (game.Players.existsUID(data)) {
                player = game.Players.getByUID(data);
                player.disconnected = false;
            } else {
                //timed out, create new player
            }
        } else {
            //localStorage is not set, create new player
        }
    });

    socket.on('disconnect', function () {
        player.disconnected = true;
        setTimeout(function () {
            if (player.disconnected) player.delete();
        }, 10000);
    });
});
2020-07-07