Search code examples
phpmysqlonline-game

Update database when user is no more online


I am currently working on a Javascript multiplayer game.

When users want to play, they enter a waiting room where they wait for players to play with.

It is stored in a SQL database this way : I have a table named USER with some data on the players, and another table named WAITINGROOM which associates the id USERID of the user waiting for a game with other infos.

When players leave the waiting room or close their browser, I delete the row with their id in table WAITINGROOM.

But let's suppose the user loses his internet connection while looking for a game. How can I know he is offline so I can remove the row containing his id ?

The player is offline so it is definitely not client side I can deal with this. Maybe server side in PHP ? Or directly in the database using timeouts or something...


Solution

  • I assume you have a script (probably called via ajax) which fetches the online users for the current user. Simply add a column like 'last_seen_online' with a timestamp. Update the field every time the user calls this script. Now you can filter it in your sql for example get all users which have been online during the last minute. - Everything not active since one minute is considered offline like this.

    To get rid of users which went offline you can implement a garbage collection(like php with sessions does). You grab all users which havent been seen since the last (for example)5 minutes. You place this garbage collection in the same script. To keep the load low. You dont call it every time, just like 50% of the time with if(rand(1,100) > 50) or any percentage you like.