How do you parallelize async udp socket?

With TcpListener, one standard way to parallelize is to:

  1. main async task creates TcpListener, waits for streams
  2. for each stream, we fire off a new async task to handle that particular stream

With UdpSocket, we bind to a port and then we wait for packets on the port. How do we parallelize this? Is it one spawn task per packet (not sure what the overhead of spawn here is) or something else ?

Place in Arc and spawn/send-to tasks. It is Send/Sync and has shared methods.

So we start with this:

    pub async fn start_udp_server() -> anyhow::Result<()> {
        let socket = tokio::net::UdpSocket::bind("127.0.0.1:7001").await?;
        println!("Listening on {}", socket.local_addr()?);
        let mut buf = vec![0u8; 1024];
        loop {
            let (recv, peer) = socket.recv_from(&mut buf).await?;
            let sent = socket.send_to(&buf[..recv], &peer).await?;
            println!("Sent {} out of {} bytes to {}", sent, recv, peer);}}

Is your suggestion:

  1. put the socket into an Arc
  2. spawn a fixed # of tasks (say # of cores)
  3. have each core run the loop of
     loop {
            let (recv, peer) = socket.recv_from(&mut buf).await?;
            let sent = socket.send_to(&buf[..recv], &peer).await?;
            println!("Sent {} out of {} bytes to {}", sent, recv, peer);}