我正在嘗試使用 UDP 作為協(xié)議在兩臺計算機之間創(chuàng)建一條雙向街道。也許我不明白 net.ListenUDP 的意義。這不應該是一個阻塞調(diào)用嗎?等待客戶端連接?addr := net.UDPAddr{ Port: 2000, IP: net.ParseIP("127.0.0.1"),}conn, err := net.ListenUDP("udp", &addr)// code does not block heredefer conn.Close()if err != nil { panic(err)}var testPayload []byte = []byte("This is a test")conn.Write(testPayload)
1 回答

30秒到達戰(zhàn)場
TA貢獻1828條經(jīng)驗 獲得超6個贊
它不會阻塞,因為它在后臺運行。然后你只需從連接中讀取。
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)
檢查這個答案。它有一個 UDP 連接的工作示例,以及一些使其工作得更好的技巧。
- 1 回答
- 0 關注
- 391 瀏覽
添加回答
舉報
0/150
提交
取消