Im storing the socketID of the current connection in the session, so I always know the current socketIDs of the connected clients, even if they refresh the page. Now I have a timer and when the timer ends I want to log the current socketID and if I refresh the page before the timer ends I want to log the new ID.
To share the session between express and socket.io I use express-socket.io-session so I can edit the session within the socket.io connection. After every connection I save or update the current socketID of the client in the session. Im using mongoDB to store the sessions locally. It is working fine for me. However it is not working if I refresh the page while the timer is still going.
io.on('connection', (socket) => {
// save or update socketID after every new connection
const sID = socket.id;
socket.handshake.session.sID = sID;
socket.handshake.session.save(); //current socketID saved in session
console.log('Current sID: ' + socket.handshake.session.sID);
function time() {
var sec = 10;
console.log('Timer started');
var timer = setInterval(function() {
if(sec == 0) {
console.log('Current sID: ' + socket.handshake.session.sID);
clearInterval(timer);
}
sec--;
}, 1000);
}
socket.on('startTimer', () => {
time();
});
}
Console:
// Start timer without refreshing
Current sID: 3IgL6yujje9axyYVAAAA // new connection
Timer started
Current sID: 3IgL6yujje9axyYVAAAA // stored ID
// session Store in Mongo
{
"_id" : "HFmatIQpCQ9W-A0gGhr4wNUX_aau5Hun",
"expires" : ISODate("2019-09-15T09:29:37.853Z"),
"session" : "{\"cookie\":{\"originalMaxAge\":null,\"expires\":null,\"httpOnly\":true,\"path\":\"/\"},
\"sID\":\"3IgL6yujje9axyYVAAAA\"}"
}
// Everything worked
// Start timer with refreshing
Timer started
Current sID: s7ih8Aa_JStYD0rJAAAB // new ID because of refresh
Current sID: 3IgL6yujje9axyYVAAAA // timer ends. Logs old ID
// session Store in Mongo with new ID
{
"_id" : "HFmatIQpCQ9W-A0gGhr4wNUX_aau5Hun",
"expires" : ISODate("2019-09-15T09:33:41.289Z"),
"session" : "{\"cookie\":{\"originalMaxAge\":null,\"expires\":null,\"httpOnly\":true,\"path\":\"/\"},
\"sID\":\"s7ih8Aa_JStYD0rJAAAB\"}"
}
// New ID is stored, but got old ID
As you can see when I start the timer and do nothing it just logs the stored socketID as expected. But if I refresh the page while the timer is still going it does not log the new ID even though the new ID is already updated in the session. It logs the ID the socket had before I started the timer and refreshed the page. Is it something with the scope? Hope there is a simple answer