2022-06-05 20:45:19 +02:00
|
|
|
use std::{net::{TcpStream, TcpListener}, io::prelude::*, fs, env};
|
2022-06-04 19:22:41 +02:00
|
|
|
|
|
|
|
|
|
|
|
fn main() {
|
2022-06-05 20:45:19 +02:00
|
|
|
let args: Vec<String> = env::args().collect();
|
2022-06-04 19:22:41 +02:00
|
|
|
|
2022-06-05 20:45:19 +02:00
|
|
|
let host = if args.len() < 2 {
|
|
|
|
"127.0.0.1:6666"
|
|
|
|
} else {
|
|
|
|
&args[1]
|
|
|
|
};
|
|
|
|
println!("Starting server on {:?}...\n", &host);
|
|
|
|
|
|
|
|
let listener = TcpListener::bind(host).expect("Could not bind to address");
|
2022-06-04 19:22:41 +02:00
|
|
|
|
2022-06-05 20:45:19 +02:00
|
|
|
for stream in listener.incoming() {
|
|
|
|
if let Ok(stream) = stream {
|
|
|
|
handle_connection(stream);
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
println!("Error with incoming stream: {}", stream.err().unwrap());
|
|
|
|
}
|
2022-06-04 19:22:41 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
fn handle_connection(mut stream: TcpStream) {
|
|
|
|
let mut buffer = vec![0; 1024];
|
|
|
|
let size = stream.read(&mut buffer).unwrap();
|
|
|
|
buffer.resize(size, 0);
|
2022-06-05 20:45:19 +02:00
|
|
|
|
|
|
|
let contents = fs::read_to_string("src/main.rs").unwrap() + "\n\n";
|
2022-06-04 19:22:41 +02:00
|
|
|
|
|
|
|
let response = format!(
|
|
|
|
"HTTP/1.1 200 OK\nContent-Length: {}\n\n{}",
|
|
|
|
contents.len() + buffer.len(),
|
|
|
|
contents
|
|
|
|
);
|
2022-06-05 20:45:19 +02:00
|
|
|
stream.write_all(response.as_bytes()).unwrap();
|
|
|
|
stream.write_all(&buffer).unwrap();
|
2022-06-04 19:22:41 +02:00
|
|
|
stream.flush().unwrap();
|
2022-06-05 20:45:19 +02:00
|
|
|
|
|
|
|
let peer_addr = stream.peer_addr().unwrap();
|
|
|
|
println!("Received {} bytes from {}\n\n{}\n", size, peer_addr,
|
2022-06-04 19:22:41 +02:00
|
|
|
String::from_utf8_lossy(&buffer)
|
|
|
|
.escape_debug()
|
|
|
|
.collect::<String>()
|
|
|
|
.replace("\\r\\n", "\n")
|
|
|
|
.replace("\\n", "\n")
|
|
|
|
);
|
|
|
|
}
|