From 6017a6ca47cabfa27e2f5fe293b0fda607540150 Mon Sep 17 00:00:00 2001 From: Martin Brodbeck Date: Tue, 3 Oct 2023 19:53:32 +0200 Subject: [PATCH] most is implemented --- src/main.rs | 59 ++++++++++++++++++++++++++++++++++++++++++----------- 1 file changed, 47 insertions(+), 12 deletions(-) diff --git a/src/main.rs b/src/main.rs index 06dd61f..74e3942 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,4 +1,4 @@ -use chrono::{DateTime, Local}; +use chrono::{DateTime, Local, Duration}; use std::{ collections::{HashMap, HashSet}, net::UdpSocket, @@ -25,7 +25,7 @@ fn strip_header(msg: &[u8]) -> Vec { let mut stripped = Vec::new(); stripped.push(msg[1] & 3); stripped.append(msg[2..].to_vec().as_mut()); - print_msg(&stripped); + //print_msg(&stripped); stripped.to_owned() } @@ -100,16 +100,41 @@ fn mopp(speed: u8, data: &[u8]) -> Vec { m.push_str("00"); // EOC } - m.push_str("11"); // EOW + m.replace_range(m.len() - 2.., "11"); // EOW - println!("MOPP: {1:0$}", (8 as f32 * (m.len() as f32 / 8 as f32).ceil()) as usize, m); + println!( + "MOPP: {1:0$}", + (8 as f32 * (m.len() as f32 / 8 as f32).ceil()) as usize, + m + ); - m.as_bytes().to_owned() + m = format!( + "{1:0<0$}", + (8 as f32 * (m.len() as f32 / 8 as f32).ceil()) as usize, + m + ); + + let mut res = Vec::::new(); + for i in (0..m.len()).step_by(8) { + let value = u8::from_str_radix(&m[i..i + 8], 2).unwrap(); + res.push(value); + } + + res.to_owned() } -fn broadcast(socket: &UdpSocket, client: &Client, data: &[u8]) {} +fn broadcast(socket: &UdpSocket, receivers: &HashSet, client: &Client, data: &[u8]) { + for rec in receivers { + // Do not broadcast to origin + if rec.name == client.name { + continue; + } + socket.send_to(&data, &rec.name).unwrap(); + } +} fn main() -> std::io::Result<()> { + let socket = UdpSocket::bind("0.0.0.0:7373")?; socket .set_read_timeout(None) @@ -130,23 +155,33 @@ fn main() -> std::io::Result<()> { let data = &buf[0..number_of_bytes]; - println!("Data: {:?}", strip_header(data)); - println!("Repl: {:?}", strip_header(mopp(speed, b"hi").as_slice())); - if receivers.iter().any(|x| x.name == client_addr) { println!("Client already known."); + broadcast(&socket, &receivers, &client, data); } else if strip_header(data) == strip_header(mopp(speed, b"hi").as_slice()) { println!("Welcome!"); if receivers.len() < MAX_CLIENTS { receivers.insert(client.clone()); - // TODO: welcome socket .send_to(mopp(speed, b"hi").as_slice(), &client.name) .unwrap(); } else { - // TODO: reject - println!("Unknown client - Ignoring"); + socket + .send_to(mopp(speed, b":qrl").as_slice(), &client.name) + .unwrap(); + } + } else { + println!("Unknown client - Ignoring"); + } + + let timestamp = Local::now(); + for cl in &receivers { + if cl.time + Duration::seconds(CLIENT_TIMEOUT as i64) < timestamp { + socket + .send_to(mopp(speed, b":bye").as_slice(), &client.name) + .unwrap(); } } + receivers.retain(|cl| cl.time + Duration::seconds(CLIENT_TIMEOUT as i64) >= timestamp); } }