英文:
Create multiple UDP servers using golang
问题
我有一个端口列表,需要创建一个UDP服务器。我尝试了以下方法:
for _, r := range routingTable.Routes {
if r.Metric == 0 {
wg.Add(1)
go func() {
conn, err := net.ListenUDP("udp4", &r.OriginPort)
if err != nil {
log.Fatalf("启动服务器时出错:%s", err)
} else {
log.Printf("监听端口:%s", r.OriginPort.String())
}
defer conn.Close()
buffer := make([]byte, 1024)
for {
conn.ReadFromUDP(buffer)
}
}()
wg.Wait()
}
}
但是它没有起作用。我该怎么做才能使其工作?
英文:
I have a list of ports that I need to create a UDP server. I have tried this aproach
for _, r := range routingTable.Routes {
if r.Metric == 0 {
wg.Add(1)
go func() {
conn, err := net.ListenUDP("udp4", &r.OriginPort)
if err != nil {
log.Fatalf("Error occured starting the server: %s", err)
} else {
log.Printf("Listening on port: %s", r.OriginPort.String())
}
defer conn.Close()
buffer := make([]byte, 1024)
for {
conn.ReadFromUDP(buffer)
}
}()
wg.Wait()
}
}
but it is not working. What can I do to make it work ?
答案1
得分: 0
- 如@CeriseLimon所指出的:不要让每次迭代都阻塞goroutine,在循环外移动
wg.Wait()
。 - 不要忘记在每个goroutine内调用
wg.Done()
:在每个函数中添加defer wg.Done()
的调用。
(由于您的监听goroutine永远不会返回,第二点有点理论性...显然,添加一些代码使您的监听goroutine执行某些操作,并在可能的情况下正常退出)
英文:
- as noted by @CeriseLimon : don't make the goroutine block on each iteration, move
wg.Wait()
outside of the loop - don't forget to call
wg.Done()
from within each goroutine : add a call todefer wg.Done()
in each function
(since your listening goroutines never return, the second point is a bit theoretical ... obviously, add some code to have your listening goroutines do something, and exit cleanly if possible)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论