now sending keepalive pakets

This commit is contained in:
Martin Brodbeck 2023-10-04 10:12:38 +02:00
parent 2622ec096d
commit 968035e2c9

View file

@ -1,9 +1,10 @@
use chrono::{DateTime, Duration, Local}; use chrono::{DateTime, Duration, Local};
use std::{collections::HashMap, net::UdpSocket, thread};
use log::debug; use log::debug;
use std::{collections::HashMap, net::UdpSocket, thread};
const MAX_CLIENTS: usize = 10;
const CLIENT_TIMEOUT: u32 = 300; const CLIENT_TIMEOUT: u32 = 300;
const KEEPALIVE: u64 = 10;
const MAX_CLIENTS: usize = 10;
const MY_SPEED: u8 = 30; const MY_SPEED: u8 = 30;
fn strip_header(msg: &[u8]) -> Vec<u8> { fn strip_header(msg: &[u8]) -> Vec<u8> {
@ -120,9 +121,7 @@ fn main() -> std::io::Result<()> {
env_logger::init(); env_logger::init();
let socket = UdpSocket::bind("0.0.0.0:7373")?; let socket = UdpSocket::bind("0.0.0.0:7373")?;
socket socket.set_read_timeout(Some(core::time::Duration::from_secs(KEEPALIVE))).expect("Could not set read timeout");
.set_read_timeout(None)
.expect("Could not set read timeout");
debug!("Morserino chat server started."); debug!("Morserino chat server started.");
@ -130,7 +129,21 @@ fn main() -> std::io::Result<()> {
loop { loop {
let mut buf = [0; 64]; 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 client_addr = src_addr.to_string();
let speed = buf[1] >> 2; let speed = buf[1] >> 2;
let data = &buf[0..number_of_bytes]; let data = &buf[0..number_of_bytes];