处理浏览器重新加载socket.io

时间:2013-11-28 07:30:35

标签: node.js socket.io sails.js

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

只有在超时后用户没有重新连接时才想在数据库中发出数据/保存用户状态

编辑:关注@Are Wojciechowski回答,我已经完成了多个标签& F5洪水处理程序

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

1 个答案:

答案 0 :(得分:29)

有一个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);
    });
});