处理浏览器重新加载 socket.io [英] Handle browser reload socket.io
本文介绍了处理浏览器重新加载 socket.io的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
socket.io有办法在disconnected事件中创建超时,然后检查用户是否已经重新连接?
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
编辑:遵循@Are Wojciechowski 的回答,我已经完成了一个多标签页&F5 洪水处理程序
Edit: Followed @Are Wojciechowski answer, I'm done with a multi tabs & F5 flood handler
https://gist.github.com/foohey/7696811
推荐答案
有一个socket.on('disconnect', function () { ... });
.所以你可以做
socket.on('disconnect', function () {
setTimeout(function () {
//do something
}, 10000);
});
<小时>
编辑 1:
我现在明白了.所以也许你应该做这样的事情:
EDIT 1:
I get it now. So maybe you should do something like this:
//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);
});
});
这篇关于处理浏览器重新加载 socket.io的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文