With TcpListener, one standard way to parallelize is to:
main async task creates TcpListener, waits for streams
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 ?
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:
put the socket into an Arc
spawn a fixed # of tasks (say # of cores)
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);}