当浏览器关闭时停止 Go 服务器。

huangapple go评论66阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2015年8月5日 19:50:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/31831703.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定