Create multiple UDP servers using golang

huangapple go评论72阅读模式
英文:

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

  1. 如@CeriseLimon所指出的:不要让每次迭代都阻塞goroutine,在循环外移动wg.Wait()
  2. 不要忘记在每个goroutine内调用wg.Done():在每个函数中添加defer wg.Done()的调用。

(由于您的监听goroutine永远不会返回,第二点有点理论性...显然,添加一些代码使您的监听goroutine执行某些操作,并在可能的情况下正常退出)

英文:
  1. as noted by @CeriseLimon : don't make the goroutine block on each iteration, move wg.Wait() outside of the loop
  2. don't forget to call wg.Done() from within each goroutine : add a call to defer 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)

huangapple
  • 本文由 发表于 2021年6月9日 00:53:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/67891347.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定