Removing old clients improved.

This commit is contained in:
Martin Brodbeck 2023-10-04 10:28:01 +02:00
parent ffbfa37ba2
commit 8d872be2a2

View file

@ -117,6 +117,24 @@ fn broadcast(
}
}
fn remove_old_clients(socket: &UdpSocket,
subscribers: &mut HashMap<String, DateTime<Local>>,) {
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);
}
}