UDP socket and keepalive messages

I have a tiny service that listens on a UDP port, does seomething with the received data and rebroadcasts it to the subscribed clients. In principle, it looks like this:

let socket = UdpSocket::bind("0.0.0.0:7373")?;
socket.set_read_timeout(None).unwrap();

loop {
  // listen on socket for incoming pakets (socket.recv_from)
  
  // do something with the data
  
  // rebroadcast the data to subscribed clients
}

So far, this works very well. I'm not a networking expert, but I guess I have to send keepalive messages in order to avoid NAT-timeouts. Is there an ideomatic way of how to implement these keepalive-pakets? I think, in Python, you can set a timeout on the socket and catch an appropriate exception. But what is the Rust-way of doing that?

recv returns a Result, so instead of catching an exception you'd match on the result and inspect the error cause to see if it was a timeout or some other unexpected error.

1 Like

I see. And if it is an error because of the timeout, I could then send the keepalive messages and return to the beginning of the loop. Thanks a lot!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.