0

I have a web game in NodeJS running socketIO. The code works but there is a glitch caused in the game due to players not disconnecting fully. What I mean by not fully being disconnected is - when a mobile player screen locks their phone, the server responds disconnected. That is great! However the client does not exit the web page in their phone browser. The problem/glitch occurs because the client might go back to the already loaded web page in their browser. The server senses this and allows them to interact with game but never triggers the io.on Connection function. The player naturally refreshes the page to get current state of game and the server stats start tweaking because refreshing triggers the io.on disconnect function first then triggers io.on connection function. This is a problem because on disconnect the server increments the playerCount negatively by one. Ultimately by not fully disconnecting aka leaving the web page loaded in memory the player sorta gets disconnecting twice before connecting. This throws off the playerCount variable. Are they any obvious or clear solutions to fix this socketio functionality?

Here are a few lines of relevant code.

 io.on('connection', function(socket){

   socket.on('newPlayer', function( playerId ){
   playerCount++;
   console.log("a user connected : " + playerCount);

if(playerCount == 1){
  arrayLocationY = location1[0];
  arrayLocationX = location1[1];
}
if(playerCount == 2){
  arrayLocationY = location2[0];
  arrayLocationX = location2[1];

 socket.on('disconnect', function(){
playerCount--;
console.log("user disconnected. Player count is now :" + playerCount);
  });

When the disconnect function is called twice it throws of playerCount cause future players to load at the wrong location. I am guess this problem is occurring because even thought the server disconnected them the already rendered html page is just waiting to reconnect thus the server doesn't respond with socket.on connection function. Any thoughts on the matter?

sirshakir
  • 129
  • 4
  • 13
  • This code is half copied and pasted. Just showing how the functionality of it works. If you need full code I can link github. – sirshakir Jan 24 '19 at 21:26

1 Answers1

0

Handled this problem with Javascript code. If the webpage tab losses focus then redirect the user to another page. Thereby when the user comes back to browser the page is no longer available.

sirshakir
  • 129
  • 4
  • 13