'How to detect when a user leaves web-game lobby

I've a basic multiplayer web-game where players get matched in a lobby of 2 when they enter the website. I'm using nodejs and express for the server side.

I want the server to detect when a player "leaves" the lobby so that i can then match the remaining player in the lobby with someone else. Leaving should include closing the tab, the browser or refreshing the page.

I tried sending an ajax request from the client side when the "unload" or "beforeunload" events fire. However i found this to be pretty inconsistent and not reliable. I've seen people use websockets for managing such client-server communications but never used them. I thought of using a timer on the server side to see if a player stops replying which might do the trick. How should i go about implementing this and how do other multiplayer web-games solve this problem?

Details about my server-side if it helps: I'm currently using express-session to decide ID's of players. Once the players are in a lobby of 2, they send continuous (every 0.5 seconds) ajax requests to the server to get information about the other player.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source