diff --git a/kubi-udp/src/client.rs b/kubi-udp/src/client.rs index 049c01b..c02bea1 100644 --- a/kubi-udp/src/client.rs +++ b/kubi-udp/src/client.rs @@ -3,7 +3,8 @@ use std::{ net::{UdpSocket, SocketAddr}, time::{Instant, Duration}, marker::PhantomData, - collections::{VecDeque, vec_deque::Drain as DrainDeque}, + collections::{VecDeque, vec_deque::Drain as DrainDeque}, + io::ErrorKind, }; use bincode::{Encode, Decode}; use crate::{ @@ -151,13 +152,13 @@ impl Client where S: Encode + Decode, R: Encode + Decode { } //receive let mut buf = Vec::new(); - loop { - if self.socket.recv(&mut buf).is_ok() { + match self.socket.recv(&mut buf) { + Ok(_) => { //TODO check the first byte of the raw data instead of decoding? let (packet, _): (IdServerPacket, _) = bincode::decode_from_slice(&buf, BINCODE_CONFIG)?; let IdServerPacket(user_id, packet) = packet; if self.client_id.map(|x| Some(x) != user_id).unwrap_or_default() { - continue + return Ok(()) } self.reset_timeout(); match packet { @@ -178,10 +179,11 @@ impl Client where S: Encode + Decode, R: Encode + Decode { self.event_queue.push_back(ClientEvent::MessageReceived(message)); } } - } else { - break - } - buf.clear(); + }, + Err(error) if error.kind() != ErrorKind::WouldBlock => { + return Err(error.into()); + }, + _ => (), } Ok(()) } diff --git a/kubi-udp/src/server.rs b/kubi-udp/src/server.rs index d2d563c..64bc97a 100644 --- a/kubi-udp/src/server.rs +++ b/kubi-udp/src/server.rs @@ -2,7 +2,8 @@ use std::{ net::{UdpSocket, SocketAddr}, time::Instant, marker::PhantomData, - collections::{VecDeque, vec_deque::Drain as DrainDeque} + collections::{VecDeque, vec_deque::Drain as DrainDeque}, + io::ErrorKind }; use anyhow::{Result, bail}; use bincode::{Encode, Decode}; @@ -113,7 +114,6 @@ impl Server where S: Encode + Decode, R: Encode + Decode { assert!(config.max_clients <= MAX_CLIENTS); let socket = UdpSocket::bind(addr)?; socket.set_nonblocking(true)?; - //socket.set_broadcast(true)?; Ok(Self { config, socket, @@ -125,8 +125,8 @@ impl Server where S: Encode + Decode, R: Encode + Decode { pub fn update(&mut self) -> Result<()> { //TODO client timeout let mut buf = Vec::new(); - loop { - if let Ok((_, addr)) = self.socket.recv_from(&mut buf) { + match self.socket.recv_from(&mut buf) { + Ok((_, addr)) => { if let Ok(packet) = bincode::decode_from_slice(&buf, BINCODE_CONFIG) { let (packet, _): (IdClientPacket, _) = packet; let IdClientPacket(id, packet) = packet; @@ -177,10 +177,11 @@ impl Server where S: Encode + Decode, R: Encode + Decode { } else { bail!("Corrupted packet received"); } - } else { - break - } - buf.clear() + }, + Err(error) if error.kind() != ErrorKind::WouldBlock => { + return Err(error.into()); + }, + _ => (), } Ok(()) }