UDP in golang, Listen not a blocking call?

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

UDP in golang, Listen not a blocking call?

问题

我正在尝试使用UDP作为协议在两台计算机之间创建双向通信。也许我没有理解net.ListenUDP的作用。这不应该是一个阻塞调用吗?等待客户端连接?

  1. addr := net.UDPAddr{
  2. Port: 2000,
  3. IP: net.ParseIP("127.0.0.1"),
  4. }
  5. conn, err := net.ListenUDP("udp", &addr)
  6. // 代码在这里不会阻塞
  7. defer conn.Close()
  8. if err != nil {
  9. panic(err)
  10. }
  11. var testPayload []byte = []byte("This is a test")
  12. conn.Write(testPayload)
英文:

I'm trying to create a two way street between two computers using UDP as a protocol. Maybe I'm not understanding the point of net.ListenUDP. Shouldn't this be a blocking call? Waiting for a client to connect?

  1. addr := net.UDPAddr{
  2. Port: 2000,
  3. IP: net.ParseIP("127.0.0.1"),
  4. }
  5. conn, err := net.ListenUDP("udp", &addr)
  6. // code does not block here
  7. defer conn.Close()
  8. if err != nil {
  9. panic(err)
  10. }
  11. var testPayload []byte = []byte("This is a test")
  12. conn.Write(testPayload)

答案1

得分: 12

它不会阻塞,因为它在后台运行。然后你只需要从连接中读取数据。

  1. addr := net.UDPAddr{
  2. Port: 2000,
  3. IP: net.ParseIP("127.0.0.1"),
  4. }
  5. conn, err := net.ListenUDP("udp", &addr) // 代码不会在这里阻塞
  6. if err != nil {
  7. panic(err)
  8. }
  9. defer ln.Close()
  10. var buf [1024]byte
  11. for {
  12. rlen, remote, err := conn.ReadFromUDP(buf[:])
  13. // 处理读取到的字节
  14. }
  15. var testPayload []byte = []byte("This is a test")
  16. conn.Write(testPayload)

查看这个答案。它提供了一个在Go中使用UDP连接的工作示例和一些改进的提示。

英文:

It isn't blocking because it runs in the background. Then you just read from the connection.

  1. addr := net.UDPAddr{
  2. Port: 2000,
  3. IP: net.ParseIP("127.0.0.1"),
  4. }
  5. conn, err := net.ListenUDP("udp", &addr) // code does not block here
  6. if err != nil {
  7. panic(err)
  8. }
  9. defer ln.Close()
  10. var buf [1024]byte
  11. for {
  12. rlen, remote, err := conn.ReadFromUDP(buf[:])
  13. // Do stuff with the read bytes
  14. }
  15. var testPayload []byte = []byte("This is a test")
  16. conn.Write(testPayload)

Check this answer. It has a working example of UDP connections in go and some tips to make it work a little better.

huangapple
  • 本文由 发表于 2014年11月28日 01:52:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/27176523.html
匿名

发表评论

匿名网友

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

确定