UDP Datagrams Dial Write Read Roundtrip
DialUDP pins a UDP peer so Write and Read address the same endpoint; a listener echoes by source address and SetReadDeadline bounds possible drops.
Code
package main
import (
"fmt"
"net"
"time"
)
func main() {
// 应答端:ListenUDP 收数据报,按来源地址回发
server, err := net.ListenUDP("udp", &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 0})
if err != nil {
panic(err)
}
defer server.Close()
go func() {
buf := make([]byte, 512)
for {
n, addr, err := server.ReadFromUDP(buf)
if err != nil {
return
}
server.WriteToUDP(buf[:n], addr)
}
}()
// 发送端:DialUDP 固定对端,Write/Read 都面向同一地址
client, err := net.DialUDP("udp", nil, server.LocalAddr().(*net.UDPAddr))
if err != nil {
panic(err)
}
defer client.Close()
for i := 0; i < 3; i++ {
msg := fmt.Sprintf("packet-%d", i)
if _, err := client.Write([]byte(msg)); err != nil {
panic(err)
}
// UDP 可能丢包:读截止兜底,超时走重试而不是永久阻塞
if err := client.SetReadDeadline(time.Now().Add(time.Second)); err != nil {
panic(err)
}
buf := make([]byte, 512)
n, err := client.Read(buf)
if err != nil {
fmt.Println("no reply in 1s, would retry")
continue
}
fmt.Println("reply:", string(buf[:n]))
}
}Inside the snippet
Count the function main as the entire surface area of UDP Datagrams Dial Write Read Roundtrip.
for carries the per-item work. The 6 err checkpoints do not all abort: 4 of them call panic(err) (ListenUDP, DialUDP, the client-side Write, SetReadDeadline), while the echo goroutine’s ReadFromUDP failure just returns — that read loop ends quietly instead of crashing the process. The client’s Read error is handled rather than fatal: after SetReadDeadline, a missed reply prints no reply in 1s, would retry and continues to the next packet, so the deadline-plus-retry path this snippet exists to demonstrate is real and reachable. Work is dispatched on a goroutine. defer schedules the cleanup, and the scheduled call fires no matter how the function exits.
What to watch for
- Nothing third-party is pulled in; the snippet is dependency-free.
- 4 of the 6 checkpoints
panic(err); the echo goroutine exits quietly on a read error, and a 1s client timeout is answered with a retry, not an abort.
Putting it to use
Entry signature: func main()
The demo output is labeled (reply: packet-0 on a round trip, no reply in 1s, would retry when the 1s deadline expires) — each line names the round that produced it.
Lines that carry the logic
if err != nil {
panic(err)
}
if err != nil {
return
}
if err != nil {
fmt.Println("no reply in 1s, would retry")
continue
}
Interactive Tools for This Topic
FAQ
- How does the code signal failure?
- Through `panic(err)` — the 6 checkpoints test `err` and abort the run on the first non-nil one.
- What does UDP Datagrams Dial Write Read Roundtrip print when run?
- Run it as a complete program — the output lines carry labels such as `no reply in 1s, would retry`, `reply:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.