You can use a timeout delay and the socket disconnection event to make it easier to disconnect and reconnect.
When your socket connects, add them to a bucket object.
if (socket.request.sessionID && !bucket[socket.request.sessionID]) {
bucket[socket.request.session.player.id] = socket.id; //nuuu they stealin mah bukkit
}
This adds the player's id (which I track through node session tethered into the socket) as a key to the socketId
//object for delayed log out
let disconnection = {
sid : null, //socket id
delay : null //timeout id
};
Create an object that stores your socket ID so you can track who was disconnected.
socket.on('disconnect', function () {
disconnection.sid = socket.request.sessionID; //grab session id
disconnection.delay = setTimeout(() => {
//set timeout to variable, in case of reconnection
delete bucket[socket.request.sessionID];
//emit the disconnection event
}, 60000);
});
When the user disconnects, set a timeout for however long they have to reconnect.
Upon reconnection, simply do:
io.sockets.on("connection", socket => {
//check for disconnection, compare socket ids, and remove timeout if sockets match
if (disconnection.delay && disconnection.sid == socket.request.sessionID) {
clearTimeout(disconnection.delay);
disconnection.sid = null;
}
});
This will check the reconnection for an existing socketID and clear the timeout, successfully establishing the connection once more.
Note that this code is a copy of SourceUndead (my game) so some of it might not directly translate to you (for instance, my socket variable is bound with the session as well), but the concept of a timeout disconnection is the same.