英文:
Continuously check if tcp port is in use
问题
我正在运行一个bash命令来在后台启动一个服务器:"./starServer &"。然而,我的服务器需要几秒钟的时间来启动。我想知道在实际继续执行其他操作之前,我可以做些什么来持续检查它所运行的端口,以确保它已经启动。我在golang API中找不到任何有用的内容。感谢任何帮助!
c := exec.Command("/bin/sh", "-c", command)
err := c.Start()
if err != nil {
log.Fatalf("error: %v", err)
}
l, err1 := net.Listen("tcp", ":"+port)
英文:
I'm running a bash command to start up a server in the background : "./starServer &" However, my server takes a few seconds to start up. I'm wondering what I can do to continuously check the port that it's running on to ensure it's up before I actually move on and do other things. I couldn't find anything in the golang api that helped with this. Any help is appreciated!
c := exec.Command("/bin/sh", "-c", command)
err := c.Start()
if err != nil {
log.Fatalf("error: %v", err)
}
l, err1 := net.Listen("tcp", ":" + port)
答案1
得分: 18
你可以使用net.DialTimeout
或net.Dial
连接到端口,如果成功,立即关闭连接。你可以在一个循环中执行这个操作,直到成功。
for {
conn, err := net.DialTimeout("tcp", net.JoinHostPort("", port), timeout)
if conn != nil {
conn.Close()
break
}
}
我写了一个类似目的的简单小型库,也许你会感兴趣:portping
。
英文:
You could connect to the port using net.DialTimeout
or net.Dial
, and if successful, immediately close it. You can do this in a loop until successful.
for {
conn, err := net.DialTimeout("tcp", net.JoinHostPort("", port), timeout)
if conn != nil {
conn.Close()
break
}
}
A simple tiny library (I wrote) for a similar purpose might also be of interest: portping
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论