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
In the first case, the Socket will automatically try to reconnect, after a given delay.
Socket disconnects automatically, reconnects, and disconnects again and form a loop. #918.
Although Socket.IO indeed uses WebSocket for transport when possible, it adds additional metadata to each packet. That is why a WebSocket client will not be able to successfully connect to a Socket.IO server, and a Socket.IO client will not be able to connect to a plain WebSocket server either.
There is a socket.on('disconnect', function () { ... });
. So you can just do
socket.on('disconnect', function () { setTimeout(function () { //do something }, 10000); });
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); }); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With