UDP Datagram Roundtrip With UdpSocket

Exchange datagrams over loopback with UdpSocket, learning how connectionless peers, packet boundaries, and source addresses behave.

RustData Fetching

Code

rustsnippet
27 lines
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 Result values 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

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`.