From 8d872be2a26fab947f9dc243980c878d6137bddc Mon Sep 17 00:00:00 2001 From: Martin Brodbeck Date: Wed, 4 Oct 2023 10:28:01 +0200 Subject: [PATCH] Removing old clients improved. --- src/main.rs | 30 ++++++++++++++++++++---------- 1 file changed, 20 insertions(+), 10 deletions(-) diff --git a/src/main.rs b/src/main.rs index 4e56d33..1bcaf8d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -117,6 +117,24 @@ fn broadcast( } } +fn remove_old_clients(socket: &UdpSocket, + subscribers: &mut HashMap>,) { + let timestamp = Local::now(); + + debug!("Number of clients: {}", subscribers.len()); + + for cl in &*subscribers { + if *cl.1 + Duration::seconds(CLIENT_TIMEOUT as i64) < timestamp { + debug!("Removing old client {}", cl.0); + socket + .send_to(mopp(MY_SPEED, b":bye").as_slice(), &cl.0) + .unwrap(); + } + } + + subscribers.retain(|_, val| *val + Duration::seconds(CLIENT_TIMEOUT as i64) >= timestamp); + } + fn main() -> std::io::Result<()> { env_logger::init(); @@ -137,6 +155,7 @@ fn main() -> std::io::Result<()> { let (number_of_bytes, src_addr) = match result { Ok((num, s)) => (num, s), Err(_) => { + remove_old_clients(&socket, &mut subscribers); debug!("Sending keepalive pakets …"); for rec in &subscribers { socket.send_to(b"", rec.0).unwrap(); @@ -184,15 +203,6 @@ fn main() -> std::io::Result<()> { debug!("Ignoring unknown client {client_addr}"); } - let timestamp = Local::now(); - for cl in &subscribers { - if *cl.1 + Duration::seconds(CLIENT_TIMEOUT as i64) < timestamp { - debug!("Removing outdated client {}", cl.0); - socket - .send_to(mopp(MY_SPEED, b":bye").as_slice(), &client_addr) - .unwrap(); - } - } - subscribers.retain(|_, val| *val + Duration::seconds(CLIENT_TIMEOUT as i64) >= timestamp); + remove_old_clients(&socket, &mut subscribers); } }