e2e-irc/src/listener_server.rs

59 lines
1.9 KiB
Rust
Raw Normal View History

2023-10-07 13:27:38 +02:00
use std::io::{ErrorKind, Read, Write};
use std::net::{TcpListener, TcpStream};
use std::sync::mpsc::{self, TryRecvError};
2023-10-12 13:59:07 +02:00
use std::thread;
use std::time::Duration;
fn stream_handler(tx: &mpsc::Sender<String>, rx: &mpsc::Receiver<String>, mut stream: TcpStream) {
loop {
let mut buffer: Vec<u8> = Vec::new();
let mut buf: [u8; 1] = [0];
let newline: u8 = b'\n';
while buf[0] != newline {
match stream.read(&mut buf) {
2023-10-07 13:27:38 +02:00
Ok(_length) => buffer.push(buf[0]),
Err(_error) => match _error.kind() {
2023-10-12 13:59:07 +02:00
ErrorKind::WouldBlock => {}
2023-10-07 13:27:38 +02:00
_ => {
dbg!(_error);
return;
2023-10-07 13:27:38 +02:00
}
},
}
match rx.try_recv() {
Ok(value) => {
match stream.write_all(value.as_bytes()) {
Ok(_) => {}
Err(_e) => {
dbg!(_e);
return;
}
};
}
2023-10-19 17:08:05 +02:00
Err(TryRecvError::Empty) => {}
Err(TryRecvError::Disconnected) => return,
}
2023-10-12 22:01:17 +02:00
thread::sleep(Duration::from_micros(100));
}
2023-10-19 17:08:05 +02:00
let _ = tx.send(dbg!(String::from_utf8_lossy(&buffer).to_string()));
}
}
pub fn listen_to_client(tx: mpsc::Sender<String>, rx: mpsc::Receiver<String>, 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}");
}
}