UDP Datagram Roundtrip With UdpSocket
Exchange datagrams over loopback with UdpSocket, learning how connectionless peers, packet boundaries, and source addresses behave.
Code
use std::net::UdpSocket;
use std::thread;
fn main() -> std::io::Result<()> {
let server = UdpSocket::bind("127.0.0.1:0")?;
let server_addr = server.local_addr()?;
println!("udp server on {server_addr}");
let worker = thread::spawn(move || -> std::io::Result<()> {
let mut buf = [0u8; 512];
// recv_from 同时返回数据和发送方地址
let (n, peer) = server.recv_from(&mut buf)?;
let text = String::from_utf8_lossy(&buf[..n]).to_uppercase();
server.send_to(text.as_bytes(), peer)?;
Ok(())
});
let client = UdpSocket::bind("127.0.0.1:0")?;
// 每条数据报独立寻址,没有连接握手
client.send_to(b"hello datagram", server_addr)?;
let mut buf = [0u8; 512];
let (n, from) = client.recv_from(&mut buf)?;
println!("reply from {from}: {}", String::from_utf8_lossy(&buf[..n]));
worker.join().unwrap()?;
Ok(())
}How the snippet works
UDP Datagram Roundtrip With UdpSocket comes down to the function main.
Result turns the error into data — visible in the type, handled by the caller.
Points of care
- The
Resultvalues will not let errors pass silently; each must be matched, unwrapped, or propagated.
Applying it
The primary signature is fn main() -> std::io::Result<()>
Running the file prints labeled results such as udp server on, reply from — each operation’s effect is visible in the output.
Statements that matter
worker.join().unwrap()?;
let worker = thread::spawn(move || -> std::io::Result<()> {
let mut buf = [0u8; 512];
// recv_from 同时返回数据和发送方地址
let (n, peer) = server.recv_from(&mut buf)?;
let text = String::from_utf8_lossy(&buf[..n]).to_uppercase();
server.send_to(text.as_bytes(), peer)?;
Ok(())
});
client.send_to(b"hello datagram", server_addr)?;
Interactive Tools for This Topic
DSN Connection String ParserParse PostgreSQL, MySQL, Redis, MongoDB, and AMQP DSN URLs locally with masked credentials, multi-host support, default ports, and SSL/pool inspection.IPv4 Subnet CalculatorCalculate network and broadcast addresses, netmask, wildcard, and usable host range from an IPv4 address in CIDR notation.
FAQ
- How do errors reach the caller?
- Through the type system: failures are `Result` variants the caller must consume.
- What does UDP Datagram Roundtrip With UdpSocket print when run?
- The script runs standalone; its 2 labeled outputs include `udp server on`, `reply from`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.