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); } }