tcp 客户端未到达某些语句就结束
tcp client ends without reaching some statements
下面的代码假设打开到服务器的连接,发送消息并在结束前等待回复,但问题是它甚至没有到达函数的末尾。有什么问题吗?我应该使用 wg sync.WaitGroup
吗?
func client(servId uint16, servAddr string) {
tcpAddr, err := net.ResolveTCPAddr("tcp", servAddr)
check(err)
conn, err := net.DialTCP("tcp", nil, tcpAddr)
check(err)
_, err = conn.Write(handshake(servId, 1500))
check(err)
init := make([]byte, 8)
_, err = io.ReadFull(conn, init)
check(err)
fmt.Println("is reached") // doesn't get printed WHY?
fmt.Println(init)
}
如何从 main
调用上面的函数
// vars
var c, startId, servId uint16
// for each servers
for s := 0; s < len(config.Servers); s++ {
// for each connection
for c = 0; c < config.Total_clients; c++ {
startId = config.Server_id * config.Total_clients
servId = startId + c
servAddr := fmt.Sprintf("%s:%d", config.Servers[s].Host, config.Servers[s].Port)
// create the clients in new go routines
go client(servId, servAddr)
}
}
你的程序会在执行完之前退出,你需要使用sync.WaitGroup
或者channels等待所有输出后再退出。
func client(wg *sync.WaitGroup, servId uint16, servAddr string) {
defer wg.Done()
.....
}
func main() {
var (
c, startId, servId uint16
wg sync.WaitGroup
)
for _, srv := range config.Servers {
for c = 0; c < config.Total_clients; c++ {
......
wg.Add(1)
go client(&wg, servId, servAddr)
}
}
wg.Wait()
}
下面的代码假设打开到服务器的连接,发送消息并在结束前等待回复,但问题是它甚至没有到达函数的末尾。有什么问题吗?我应该使用 wg sync.WaitGroup
吗?
func client(servId uint16, servAddr string) {
tcpAddr, err := net.ResolveTCPAddr("tcp", servAddr)
check(err)
conn, err := net.DialTCP("tcp", nil, tcpAddr)
check(err)
_, err = conn.Write(handshake(servId, 1500))
check(err)
init := make([]byte, 8)
_, err = io.ReadFull(conn, init)
check(err)
fmt.Println("is reached") // doesn't get printed WHY?
fmt.Println(init)
}
如何从 main
// vars
var c, startId, servId uint16
// for each servers
for s := 0; s < len(config.Servers); s++ {
// for each connection
for c = 0; c < config.Total_clients; c++ {
startId = config.Server_id * config.Total_clients
servId = startId + c
servAddr := fmt.Sprintf("%s:%d", config.Servers[s].Host, config.Servers[s].Port)
// create the clients in new go routines
go client(servId, servAddr)
}
}
你的程序会在执行完之前退出,你需要使用sync.WaitGroup
或者channels等待所有输出后再退出。
func client(wg *sync.WaitGroup, servId uint16, servAddr string) {
defer wg.Done()
.....
}
func main() {
var (
c, startId, servId uint16
wg sync.WaitGroup
)
for _, srv := range config.Servers {
for c = 0; c < config.Total_clients; c++ {
......
wg.Add(1)
go client(&wg, servId, servAddr)
}
}
wg.Wait()
}