1 回答
TA贡献1851条经验 获得超5个赞
当main函数返回时,Go 程序退出。
简单的解决方法是sendRequest直接调用。这个程序不需要goroutine。
func main() {
conn, err := net.Dial("tcp", "localhost:8081")
if err != nil {
fmt.Println(err);
conn.Close();
}
fmt.Println("Got connection, type anything...new line sends and quit quits the session");
sendRequest(conn) // <-- go removed from this line.
}
如果需要够程,然后用sync.WaitGroup使main等待够程来完成:
func main() {
conn, err := net.Dial("tcp", "localhost:8081")
if err != nil {
fmt.Println(err);
conn.Close();
}
var wg sync.WaitGroup
fmt.Println("Got connection, type anything...new line sends and quit quits the session");
wg.Add(1)
go sendRequest(&wg, conn)
wg.Wait()
}
func sendRequest(wg *sync.WaitGroup, conn net.Conn) {
defer wg.Done()
// same code as before
}
- 1 回答
- 0 关注
- 236 浏览
添加回答
举报