From ab7d0d4d2ed7680e777d71217d65d9e9b340349d Mon Sep 17 00:00:00 2001 From: Greg Burri Date: Sat, 21 Oct 2023 21:43:04 +0200 Subject: [PATCH] Retry when a 'WouldBlock' error is given by socket recv function --- src/main.rs | 54 ++++++++++++++++++++++++++++++----------------------- 1 file changed, 31 insertions(+), 23 deletions(-) diff --git a/src/main.rs b/src/main.rs index c7791a0..c854c74 100644 --- a/src/main.rs +++ b/src/main.rs @@ -111,37 +111,45 @@ enum PingError { } fn ping(socket: &UdpSocket, rng: &mut ThreadRng) -> std::result::Result { - let number: u64 = rng.gen(); - let mut buffer = number.to_le_bytes(); - - let now = time::Instant::now(); - match socket.send(&buffer) { - Ok(_size_sent) => { - buffer.fill(0); - match socket.recv(&mut buffer) { - Ok(size_received) => { - if size_received == 8 { - let number_received = u64::from_le_bytes(buffer); - if number_received != number { + loop { + let number: u64 = rng.gen(); + let mut buffer = number.to_le_bytes(); + let now = time::Instant::now(); + match socket.send(&buffer) { + Ok(_size_sent) => { + buffer.fill(0); + match socket.recv(&mut buffer) { + Ok(size_received) => { + if size_received == 8 { + let number_received = u64::from_le_bytes(buffer); + if number_received == number { + return Ok(time::Instant::now() - now); + } else { + return Err(PingError::WrongMessageReceived(format!( + "Message number receceived ({}) is not equal to the one sent ({})", + number_received, number + ))); + } + } else { return Err(PingError::WrongMessageReceived(format!( - "Message number receceived ({}) is not equal to the one sent ({})", - number_received, number + "Size of packet must be 8, received size: {}", + size_received ))); } - } else { - return Err(PingError::WrongMessageReceived(format!( - "Size of packet must be 8, received size: {}", - size_received - ))); } + // FIXME. + // Test the kind because sometime 'recv' returns + // '(Os { code: 11, kind: WouldBlock, message: "Resource temporarily unavailable" }'. + // Try again in this case. + Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => { + println!("WouldBlock error: {}", error) + } + Err(error) => return Err(PingError::SocketReceiveError(error)), } - Err(error) => return Err(PingError::SocketReceiveError(error)), } + Err(error) => return Err(PingError::SocketSendError(error)), } - Err(error) => return Err(PingError::SocketSendError(error)), } - - Ok(time::Instant::now() - now) } fn send_email(title: &str, body: &str, login: &str, pass: &str) -> Result<()> { -- 2.45.2