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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20260170/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:23:29  来源:igfitidea点击:

Handle browser reload socket.io

node.jssocket.iosails.js

提问by m4tm4t

There is a way in socket.io to create a timeout in the disconnected event, then check if the user has been reconnected ?

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

The idea is to emit data / save user state in database only if the user is not reconnected after timeout

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

Edit: Followed @Are Wojciechowski answer, I'm done with a multi tabs & F5 flood handler

编辑:遵循@Are Wojciechowski 的回答,我已经完成了多选项卡和 F5 洪水处理程序

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

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

回答by Are Wojciechowski

There is a socket.on('disconnect', function () { ... });. So you can just do

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

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


EDIT 1:

编辑 1:

I get it now. So maybe you should do something like this:

我现在明白了。所以也许你应该做这样的事情:

Client:

客户:

//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);

Server:

服务器:

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);
    });
});