英文:
UDP in golang, Listen not a blocking call?
问题
我正在尝试使用UDP作为协议在两台计算机之间创建双向通信。也许我没有理解net.ListenUDP的作用。这不应该是一个阻塞调用吗?等待客户端连接?
addr := net.UDPAddr{
Port: 2000,
IP: net.ParseIP("127.0.0.1"),
}
conn, err := net.ListenUDP("udp", &addr)
// 代码在这里不会阻塞
defer conn.Close()
if err != nil {
panic(err)
}
var testPayload []byte = []byte("This is a test")
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?
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)
答案1
得分: 12
它不会阻塞,因为它在后台运行。然后你只需要从连接中读取数据。
addr := net.UDPAddr{
Port: 2000,
IP: net.ParseIP("127.0.0.1"),
}
conn, err := net.ListenUDP("udp", &addr) // 代码不会在这里阻塞
if err != nil {
panic(err)
}
defer ln.Close()
var buf [1024]byte
for {
rlen, remote, err := conn.ReadFromUDP(buf[:])
// 处理读取到的字节
}
var testPayload []byte = []byte("This is a test")
conn.Write(testPayload)
查看这个答案。它提供了一个在Go中使用UDP连接的工作示例和一些改进的提示。
英文:
It isn't blocking because it runs in the background. Then you just read from the connection.
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)
Check this answer. It has a working example of UDP connections in go and some tips to make it work a little better.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论