How to Build a UDP Server and Client in Rust

Use `std::net::UdpSocket` to bind a server to an address and send/receive datagrams, while the client creates a `UdpSocket` to send data to the server's address.

How to Build a UDP Server and Client in Rust

Use std::net::UdpSocket to bind a server to an address and send/receive datagrams, while the client creates a UdpSocket to send data to the server's address.

server.rs

use std::net::UdpSocket;

fn main() {
    let socket = UdpSocket::bind("127.0.0.1:8080").unwrap();
    let mut buf = [0; 1024];
    let (len, addr) = socket.recv_from(&mut buf).unwrap();
    println!("Received {} bytes from {}: {}", len, addr, String::from_utf8_lossy(&buf[..len]));
    socket.send_to(b"Hello from server!", addr).unwrap();
}

client.rs

use std::net::UdpSocket;

fn main() {
    let socket = UdpSocket::bind("127.0.0.1:0").unwrap();
    socket.send_to(b"Hello from client!", "127.0.0.1:8080").unwrap();
    let mut buf = [0; 1024];
    let (len, _) = socket.recv_from(&mut buf).unwrap();
    println!("Received: {}", String::from_utf8_lossy(&buf[..len]));
}