From 968035e2c90be895cb7517677b056875060cc229 Mon Sep 17 00:00:00 2001 From: Martin Brodbeck Date: Wed, 4 Oct 2023 10:12:38 +0200 Subject: [PATCH] now sending keepalive pakets --- src/main.rs | 25 +++++++++++++++++++------ 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/src/main.rs b/src/main.rs index 768bfc4..4a26834 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,9 +1,10 @@ use chrono::{DateTime, Duration, Local}; -use std::{collections::HashMap, net::UdpSocket, thread}; use log::debug; +use std::{collections::HashMap, net::UdpSocket, thread}; -const MAX_CLIENTS: usize = 10; const CLIENT_TIMEOUT: u32 = 300; +const KEEPALIVE: u64 = 10; +const MAX_CLIENTS: usize = 10; const MY_SPEED: u8 = 30; fn strip_header(msg: &[u8]) -> Vec { @@ -120,9 +121,7 @@ fn main() -> std::io::Result<()> { env_logger::init(); let socket = UdpSocket::bind("0.0.0.0:7373")?; - socket - .set_read_timeout(None) - .expect("Could not set read timeout"); + socket.set_read_timeout(Some(core::time::Duration::from_secs(KEEPALIVE))).expect("Could not set read timeout"); debug!("Morserino chat server started."); @@ -130,7 +129,21 @@ fn main() -> std::io::Result<()> { loop { let mut buf = [0; 64]; - let (number_of_bytes, src_addr) = socket.recv_from(&mut buf).expect("Didn't receive data"); + + // Waiting for incoming pakets. Otherwise, after timeout, send keepalive paket + let result = socket.recv_from(&mut buf); + let (number_of_bytes, src_addr) = match result { + Ok((num, s)) => (num, s), + Err(_) => { + debug!("Sending keepalive pakets …"); + for rec in &receivers2 { + socket.send_to(b"", rec.0).unwrap(); + } + continue; + }, + }; + + let client_addr = src_addr.to_string(); let speed = buf[1] >> 2; let data = &buf[0..number_of_bytes];