简体   繁体   English

Javascript Websockets 在页面卸载时断开连接

[英]Javascript Websockets Disconnect on Page Unload

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.我正在努力使用 python Flask 和网络技术构建一个在线游戏,该技术使用网络套接字来允许游戏实时运行。 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.我认为为了让用户迅速从列表中消失,客户端的浏览器需要手动发送断开连接执行socket.disconnect()或在页面卸载时发送另一个自定义事件。

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.不幸的是,我似乎无法使用onunload事件让它运行 - 它在页面加载时运行,而不是在您离开页面时运行。 I also can't find a way to use the onbeforeunload event as I'm already using this to display a confirmation pop-up.我也找不到使用onbeforeunload事件的方法,因为我已经在使用它来显示确认弹出窗口。

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.发生的情况是,您调用socket.emit并将该调用的结果分配为事件侦听器以unload事件。 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).我设法通过强制客户端使用 websocket 传输进行连接(通过向我的io.connect函数添加{transports: ["websocket"]} io.connect {transports: ["websocket"]}标志)来io.connect正常工作。 This means that the disconnect event now works on the server.这意味着断开连接事件现在可以在服务器上运行。

NB I was required to install and use gunicorn from this point as the flask development server does not support websockets.注意,从这一点开始,我需要安装和使用 gunicorn,因为 Flask 开发服务器不支持 websockets。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM