This commit is contained in:
2024-09-25 14:50:44 +02:00
commit 72e07d5633
7 changed files with 214 additions and 0 deletions

70
client/src/main.rs Normal file
View File

@@ -0,0 +1,70 @@
use std::{
io::{self, ErrorKind, Read, Write}, net::{Shutdown, TcpStream}, process, thread
};
const BUFFER_SIZE: usize = 1024;
fn main() {
let mut socket = TcpStream::connect("127.0.0.1:42069").unwrap();
let read_socket = socket.try_clone().unwrap();
thread::spawn(move || {
handle(read_socket);
});
loop {
io::stdout().flush().unwrap();
let mut input = String::new();
match io::stdin().read_line(&mut input) {
Ok(n) => {
if n > 0 {
socket.write(input.as_bytes()).unwrap();
} else {
println!("read failed");
}
}
Err(e) => {
println!("Error: {}", e);
break;
}
}
}
}
fn handle(mut socket: TcpStream) {
loop {
let mut buf: [u8; BUFFER_SIZE] = [0; BUFFER_SIZE];
match socket.read(&mut buf) {
Ok(n) => {
let msg = String::from_utf8(buf[..n].to_vec())
.unwrap()
.trim()
.to_string();
if n <= 0 {
disconnect(socket);
return;
}
if msg.is_empty() {
continue;
}
println!("{}", msg);
}
Err(ref err) if err.kind() == ErrorKind::WouldBlock => (),
Err(_) => {
disconnect(socket);
return;
}
}
}
}
fn disconnect(socket: TcpStream) {
println!("[EVENT] Disconnected");
let _ = socket.shutdown(Shutdown::Both);
process::exit(0);
}