英文:
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") // 为什么没有打印出来?
fmt.Println(init)
}
上面的函数如何从 main
中调用:
// 变量
var c, startId, servId uint16
// 对于每个服务器
for s := 0; s < len(config.Servers); s++ {
// 对于每个连接
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)
// 在新的 Go 协程中创建客户端
go client(servId, servAddr)
}
}
英文:
The code below is suppose to open a connection to a server, send a message and wait for a reply before ending but the problem is it isn't even reaching the end of the function. What could be wrong? Should I use 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)
}
How the function above is called from 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展开收缩.Host, config.Servers展开收缩.Port)
// create the clients in new go routines
go client(servId, servAddr)
}
}
答案1
得分: 0
你的程序在执行完成之前就会退出,你需要使用sync.WaitGroup
或通道来等待所有输出完成后再退出。
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()
}
请注意,我只翻译了代码部分,其他内容已被忽略。
英文:
Your program will exit before it finishes executing, you need to use sync.WaitGroup
or channels to wait for all the output before exiting.
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()
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论