2024-01-15 17:27:50 +01:00
|
|
|
use std::{
|
2024-01-15 18:06:32 +01:00
|
|
|
io::{prelude::*, BufReader},
|
2024-01-15 17:27:50 +01:00
|
|
|
net::{TcpListener, TcpStream},
|
|
|
|
process::exit,
|
|
|
|
};
|
|
|
|
|
2024-01-15 18:06:32 +01:00
|
|
|
mod pool;
|
|
|
|
use pool::ThreadPool;
|
|
|
|
|
2024-01-15 17:27:50 +01:00
|
|
|
fn main() {
|
|
|
|
println!("Starting the server");
|
|
|
|
let target_address = "127.0.0.1:7878";
|
2024-01-15 18:06:32 +01:00
|
|
|
let pool = ThreadPool::build(4).unwrap();
|
2024-01-15 17:27:50 +01:00
|
|
|
let listener = match TcpListener::bind(target_address) {
|
|
|
|
Ok(listener) => listener,
|
|
|
|
Err(err) => {
|
|
|
|
eprintln!("Could not start server: {err}");
|
|
|
|
exit(1);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
for stream in listener.incoming() {
|
|
|
|
let stream = stream.unwrap();
|
|
|
|
|
2024-01-15 18:06:32 +01:00
|
|
|
pool.execute(|| {
|
|
|
|
handle_connection(stream);
|
|
|
|
});
|
2024-01-15 17:27:50 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn handle_connection(mut stream: TcpStream) {
|
|
|
|
let buf_rd = BufReader::new(&mut stream);
|
|
|
|
let request: Vec<_> = buf_rd
|
|
|
|
.lines()
|
|
|
|
.map(|result| result.unwrap())
|
|
|
|
.take_while(|line| !line.is_empty())
|
|
|
|
.collect();
|
|
|
|
println!("Request: {:#?}", request);
|
|
|
|
match request[0].as_str() {
|
|
|
|
"ping" => {
|
|
|
|
writeln!(stream, "> pong!").unwrap();
|
|
|
|
}
|
|
|
|
_ => {
|
|
|
|
writeln!(stream, "> command not recognized.").unwrap();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|