I have a UDP server example, which is working:
let mut socket = UdpSocket::bind("127.0.0.1:12345")?;
let mut buf = [0; 4096];
loop {
let sock = socket.try_clone()?;
match socket.recv_from(&mut buf) {
Ok((amt, src)) => {
thread::spawn(move || {
println!("Handling connection from {}", &src);
let buf = &mut buf[..amt];
buf.reverse();
sock.send_to(&buf, &src).expect("error sending");
});
},
Err(err) => {
eprintln!("Err: {}", err);
}
}
}
It looks like all incoming UDP packets are sharing the same buffer.
If two UDP packets arrive at the same time, won't the second packet overwrite the first in buf, leading to the second packet's (reversed) content being sent back to both senders?
How does Rust prevent this?