UDP in golang, Listen not a blocking call?

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

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.

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:

确定