I am working to build an online game using python flask and web technologies that uses web sockets to allow the game to run live. One page of the game is a lobby, on which all the current players are displayed. If a user disconnects from the game, they should, of course be removed from the lobby list.
I figured that in order for the user to disappear from the list promptly, the client's browser will need to manually send the disconnect executing socket.disconnect() or by sending another custom event when the page unloads.
Unfortunately I just can't seem to get this to run using the onunload event - it runs when the page loads, not when you leave the page. I also can't find a way to use the onbeforeunload event as I'm already using this to display a confirmation pop-up.
Any suggestions on this would be greatly appreciated! Thanks in advance!
My client side code:
window.addEventListener("beforeunload", function(event) {if (!intentionalForward) {event.preventDefault(); event.returnValue = " "}});
window.addEventListener("unload", function () { socket.emit("test","testing unload event"); });
What happens is, you call socket.emit and assign result of that call as event listener to unload event. You should use a closure function like this:
window.addEventListener("unload", function() { socket.emit("test","testing unload event"); });
I managed to get this working properly by forcing the client to connect using the websocket transport (by adding the {transports: ["websocket"]} flag to my io.connect function). This means that the disconnect event now works on the server.
N.B. I was required to install and use gunicorn from this point as the flask development server does not support websockets.