create a async udp server with tokio in rust

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

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

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

    loop {
        let mut buf = [0; 1024];
        let (amt, src) = socket.recv_from(&mut buf).await?;
        let buf = &buf[..amt];

        println!("Received {} bytes from {}", amt, src);
        println!("Data: {:?}", buf);

        // Echo the data back to the client
        socket.send_to(buf, &src).await?;
    }
}
540 chars
20 lines

In this code snippet, we first create a UDP socket and bind it to "127.0.0.1:8080". We then enter an infinite loop where we wait for incoming data using the recv_from method. Once we receive data, we print it out and then use the send_to method to echo the data back to the client.

The #[tokio::main] attribute on the main function signals to Tokio that this is the entry point for our async runtime.

Note that this example will block the current thread indefinitely, as it waits for incoming data. To run this example in a non-blocking way, you can spawn the task onto the Tokio runtime using tokio::spawn.

related categories

gistlibby LogSnag