英文:
Stop Go server when browser is closed
问题
我正在一台OSX机器上运行一个简单的Go服务器。当我运行命令来运行Go程序时,它会启动服务器并打开一个浏览器窗口。
我想知道是否有一种方法,当我关闭那个浏览器窗口(通过窗口而不是程序)时,也关闭服务器并退出终端。
提前谢谢。
英文:
I'm running a simple Go server on a OSX machine. When I run the command to run the Go program it starts the server and open a browser window.
I would like to know if there's a way to when I close that browser window (by the window, not the program) also close the server and quit the terminal.
Thank you in advance.
答案1
得分: 2
你可以让你的浏览器在关闭前发送一条消息,或者使用 WebSocket,但一种简单、可靠且常见的方法是设置一个 JavaScript 定时器,让浏览器定期向服务器发送心跳消息(取决于你希望服务器在浏览器关闭后多快停止;每秒、每15秒、每分钟...)。当服务器发现应该到达的消息未到达时,它可以退出。
英文:
You could let your browser emit a message before dying, or use a web socket, but a simple, reliable and usual way to do that kind of stuff is to set up a Javascript timer to have the browser send a heart-beat message to the server every now and then (depending on how quickly you want the server to stop after the browser's closing ; every second, every 15s, every minute... ?). When the server figures that a due message has not arrived, it can exit.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论