42 lines
1.3 KiB
Rust
42 lines
1.3 KiB
Rust
use std::io::{ErrorKind, Read, Write};
|
|
use std::net::TcpListener;
|
|
use std::sync::mpsc;
|
|
|
|
pub fn listen_to_client(tx: mpsc::Sender<String>, rx: mpsc::Receiver<String>, port: &str) {
|
|
let listener = TcpListener::bind("127.0.0.1:".to_string() + port).unwrap();
|
|
let mut stream = listener.accept().unwrap().0;
|
|
|
|
stream
|
|
.set_nonblocking(true)
|
|
.expect("Couldn't set nonblocking");
|
|
|
|
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) {
|
|
Ok(_length) => buffer.push(buf[0]),
|
|
Err(_error) => match _error.kind() {
|
|
ErrorKind::WouldBlock => {},
|
|
_ => {
|
|
dbg!(_error);
|
|
}
|
|
},
|
|
}
|
|
match rx.try_recv() {
|
|
Ok(value) => {
|
|
match stream.write_all(value.as_bytes()) {
|
|
Ok(_) => {}
|
|
Err(_e) => println!("Couldn't send {value}"),
|
|
};
|
|
}
|
|
Err(_e) => {}
|
|
}
|
|
}
|
|
|
|
let _ = tx.send(String::from_utf8_lossy(&buffer).to_string());
|
|
}
|
|
}
|