UDP在Golang,听不是一个阻塞调用?

yqyhoc1h  于 2023-10-14  发布在  Go
关注(0)|答案(1)|浏览(188)

我试图创建一个双向街道之间的两台计算机使用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. // 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)
clj7thdc

clj7thdc1#

它不会阻塞,因为它在后台运行。然后你就从连接中读取。

  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 conn.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)

检查this答案。它有一个在go中使用UDP连接的工作示例,以及一些使其工作得更好的提示。

展开查看全部

相关问题