create a async udp server with tokio and async main in rust

Here's an example of how to create an async UDP server using Tokio and async main in Rust:

main.rs
use tokio::net::UdpSocket;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let addr = "127.0.0.1:8080";
    let socket = UdpSocket::bind(addr).await?;

    let mut buf = [0; 1024];
    loop {
        let (len, addr) = socket.recv_from(&mut buf).await?;
        let data = &buf[..len];
        println!("Received {:?} from {:?}", data, addr);

        socket.send_to(data, &addr).await?;
    }
}
427 chars
17 lines

The main function is marked as async, allowing us to use await within the function. It binds to the UDP address 127.0.0.1:8080 using UdpSocket::bind, which returns a tokio::net::UdpSocket object.

We then enter a loop that listens for incoming data using socket.recv_from, which blocks until data is received. The received data is printed to the console, and then sent back to the client using socket.send_to.

gistlibby LogSnag