golang中的UDP,听不是阻塞呼叫?

Jon*_*ace 7 udp go

我正在尝试使用UDP作为协议在两台计算机之间创建一条双向道路.也许我不理解net.ListenUDP的观点.这不应该是阻塞电话吗?等待客户端连接?

addr := net.UDPAddr{
    Port: 2000,
    IP:   net.ParseIP("127.0.0.1"),
}
conn, err := net.ListenUDP("udp", &addr)
// code does not block here
defer conn.Close()
if err != nil {
    panic(err)
}

var testPayload []byte = []byte("This is a test")

conn.Write(testPayload)
Run Code Online (Sandbox Code Playgroud)

Top*_*opo 9

它没有阻塞,因为它在后台运行.然后你只需从连接中读取.

addr := net.UDPAddr{
    Port: 2000,
    IP:   net.ParseIP("127.0.0.1"),
}
conn, err := net.ListenUDP("udp", &addr) // code does not block here
if err != nil {
    panic(err)
}
defer ln.Close()

var buf [1024]byte
for {
    rlen, remote, err := conn.ReadFromUDP(buf[:])
    // Do stuff with the read bytes
}


var testPayload []byte = []byte("This is a test")

conn.Write(testPayload)
Run Code Online (Sandbox Code Playgroud)

检查这个答案.它有一个UDP连接的工作示例和一些提示,使其工作更好一点.

  • 你可能想在错误检查后推迟? (2认同)