golang中的UDP,Listen不是阻塞调用?

问题描述 投票:0回答:1

我正在尝试使用 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)
go udp
1个回答
12
投票

它不会阻塞,因为它在后台运行。然后您只需从连接中读取即可。

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

检查这个答案。它有一个 Go 中 UDP 连接的工作示例以及一些使其工作得更好的技巧。

© www.soinside.com 2019 - 2024. All rights reserved.