use std::net::{TcpListener, TcpStream};
use std::thread;
use std::io::{Read, Write};
pub fn handle_client(mut stream: TcpStream) {
let mut buffer = [0; 1024];
while match stream.read(&mut buffer) {
Ok(size) => {
if size > 0 {
println!("Received data: {}", String::from_utf8_lossy(&buffer[..size]));
stream.write_all(&buffer[..size]).unwrap();
true
} else {
false
}
},
Err(_) => {
println!("An error occurred, terminating connection with {}", stream.peer_addr().unwrap());
stream.shutdown(std::net::Shutdown::Both).unwrap();
false
}
} {}
}
fn main() {
let listener = TcpListener::bind("127.0.0.1:8080").expect("Could not bind to address");
for stream in listener.incoming() {
match stream {
Ok(stream) => {
println!("New connection: {}", stream.peer_addr().unwrap());
thread::spawn(move || {
handle_client(stream)
});
}
Err(e) => {
println!("Error: {}", e);
}
}
}
}