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

我正在尝试使用 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)


一只萌萌小番薯
浏览 361回答 1
1回答

30秒到达战场

它不会阻塞,因为它在后台运行。然后你只需从连接中读取。addr := net.UDPAddr{    Port: 2000,    IP:   net.ParseIP("127.0.0.1"),}conn, err := net.ListenUDP("udp", &addr) // code does not block hereif err != nil {    panic(err)}defer ln.Close()var buf [1024]bytefor {    rlen, remote, err := conn.ReadFromUDP(buf[:])    // Do stuff with the read bytes}var testPayload []byte = []byte("This is a test")conn.Write(testPayload)检查这个答案。它有一个 UDP 连接的工作示例,以及一些使其工作得更好的技巧。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go