use std::io::{ErrorKind, Read, Write}; use std::net::{TcpListener, TcpStream}; use std::sync::mpsc::{self, TryRecvError}; use std::thread; use std::time::Duration; fn stream_handler(tx: &mpsc::Sender, rx: &mpsc::Receiver, mut stream: TcpStream) { loop { let mut buffer: Vec = Vec::new(); let mut buf: [u8; 1] = [0]; let newline: u8 = b'\n'; while buf[0] != newline { match stream.read(&mut buf) { Ok(_length) => buffer.push(buf[0]), Err(_error) => match _error.kind() { ErrorKind::WouldBlock => {} _ => { dbg!(_error); return; } }, } match rx.try_recv() { Ok(value) => { match stream.write_all(value.as_bytes()) { Ok(_) => {} Err(_e) => { dbg!(_e); return; } }; } Err(TryRecvError::Empty) => {}, Err(TryRecvError::Disconnected) => return, } thread::sleep(Duration::from_micros(100)); } let _ = tx.send(String::from_utf8_lossy(&buffer).to_string()); } } pub fn listen_to_client(tx: mpsc::Sender, rx: mpsc::Receiver, port: String) { let listener = TcpListener::bind("127.0.0.1:".to_string() + &port) .expect(&("Couldn't start listener on 127.0.0.1 port ".to_string() + &port)); loop { let (stream, ip) = listener.accept().unwrap(); println!("Got connection from {ip}"); stream .set_nonblocking(true) .expect("Couldn't set nonblocking"); stream_handler(&tx, &rx, stream); println!("Closed connection with {ip}"); } }