From 26b7d1dd91722496ed6313ecbf9842596a310bca Mon Sep 17 00:00:00 2001 From: Anton Tarasenko Date: Sat, 24 Jul 2021 04:46:19 +0700 Subject: [PATCH] Add network prototype This prototype is untested, since there is currently no client to test it with. Related to #2 --- src/link/mod.rs | 56 +++++++++++++++++++++++++++++++++++++++++++++++++ src/main.rs | 14 +++++-------- 2 files changed, 61 insertions(+), 9 deletions(-) diff --git a/src/link/mod.rs b/src/link/mod.rs index 70b5e9e..610c1a0 100644 --- a/src/link/mod.rs +++ b/src/link/mod.rs @@ -1,4 +1,60 @@ +use std::error::Error; +use std::io::{Read, Write}; +use std::net::{SocketAddr, TcpListener}; +use std::sync::Arc; +use std::{str, thread}; + mod reader; mod writer; pub use reader::MessageReader; pub use writer::MessageWriter; + +pub struct Link { + reader: MessageReader, + writer: MessageWriter, +} + +impl Link { + pub fn run(port: u16, handler: F) -> Result<(), Box> + where + F: Fn(&mut Link, &str) -> () + Send + Sync + 'static, + { + let address = SocketAddr::from(([0, 0, 0, 0], port)); + let listener = TcpListener::bind(address)?; + let handler = Arc::new(handler); + loop { + // Listen to new (multiple) connection + let mut reading_stream = listener.accept()?.0; + let mut writing_stream = reading_stream.try_clone()?; + let mut avarice_link = Link { + reader: MessageReader::new(), + writer: MessageWriter::new(), + }; + let handler_clone = handler.clone(); + // On connection - spawn a new thread + thread::spawn(move || loop { + let mut buffer = [0; 1024]; + // Reading cycle + match reading_stream.read(&mut buffer) { + Ok(n) => avarice_link.reader.push(&buffer[..n]).unwrap(), + _ => panic!("Connection issue!"), + }; + // Handling cycle + while let Some(message) = avarice_link.reader.pop() { + handler_clone(&mut avarice_link, &message); + } + // Writing + avarice_link + .writer + .update_ue_received_bytes(avarice_link.reader.ue_received_bytes()); + if let Some(bytes) = avarice_link.writer.try_pop() { + writing_stream.write_all(&bytes).unwrap(); + } + }); + } + } + + pub fn write(&mut self, message: &str) { + self.writer.push(message); + } +} diff --git a/src/main.rs b/src/main.rs index 7f15ba3..9378c87 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,13 +1,9 @@ -use std::env; -use std::path::Path; mod link; -mod unreal_config; +use link::Link; fn main() { - let args: Vec = env::args().collect(); - let filename = &args[1]; - let config = unreal_config::load_file(Path::new(filename)); - if let Ok(config) = config { - print!("{}", config); - } + match Link::run(1234, |link, message| { link.write(message);}) { + Ok(_) => print!("Connect!"), + _ => print!("Connection error!"), + }; }