Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
374 views
in Technique[技术] by (71.8m points)

node.js - Handle browser reload socket.io

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

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...