add argument for port and ip, cleanup
This commit is contained in:
parent
403b15dfd9
commit
5c5496fbb7
1 changed files with 24 additions and 11 deletions
35
src/main.rs
35
src/main.rs
|
@ -1,14 +1,25 @@
|
||||||
use std::{net::{TcpStream, TcpListener}, io::prelude::*, fs};
|
use std::{net::{TcpStream, TcpListener}, io::prelude::*, fs, env};
|
||||||
|
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
let listener = TcpListener::bind("192.168.0.108:25585").unwrap();
|
let args: Vec<String> = env::args().collect();
|
||||||
|
|
||||||
|
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");
|
||||||
|
|
||||||
for stream in listener.incoming() {
|
for stream in listener.incoming() {
|
||||||
let stream = stream.unwrap();
|
if let Ok(stream) = stream {
|
||||||
println!("IP: {}\n", stream.peer_addr().unwrap());
|
handle_connection(stream);
|
||||||
|
}
|
||||||
handle_connection(stream);
|
else {
|
||||||
|
println!("Error with incoming stream: {}", stream.err().unwrap());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -17,18 +28,20 @@ fn handle_connection(mut stream: TcpStream) {
|
||||||
let mut buffer = vec![0; 1024];
|
let mut buffer = vec![0; 1024];
|
||||||
let size = stream.read(&mut buffer).unwrap();
|
let size = stream.read(&mut buffer).unwrap();
|
||||||
buffer.resize(size, 0);
|
buffer.resize(size, 0);
|
||||||
let contents = fs::read_to_string("src/main.rs").unwrap();
|
|
||||||
|
let contents = fs::read_to_string("src/main.rs").unwrap() + "\n\n";
|
||||||
|
|
||||||
let response = format!(
|
let response = format!(
|
||||||
"HTTP/1.1 200 OK\nContent-Length: {}\n\n{}",
|
"HTTP/1.1 200 OK\nContent-Length: {}\n\n{}",
|
||||||
contents.len() + buffer.len(),
|
contents.len() + buffer.len(),
|
||||||
contents
|
contents
|
||||||
);
|
);
|
||||||
|
stream.write_all(response.as_bytes()).unwrap();
|
||||||
stream.write(response.as_bytes()).unwrap();
|
stream.write_all(&buffer).unwrap();
|
||||||
stream.write(&buffer).unwrap();
|
|
||||||
stream.flush().unwrap();
|
stream.flush().unwrap();
|
||||||
println!("read {} bytes:\n{}", size,
|
|
||||||
|
let peer_addr = stream.peer_addr().unwrap();
|
||||||
|
println!("Received {} bytes from {}\n\n{}\n", size, peer_addr,
|
||||||
String::from_utf8_lossy(&buffer)
|
String::from_utf8_lossy(&buffer)
|
||||||
.escape_debug()
|
.escape_debug()
|
||||||
.collect::<String>()
|
.collect::<String>()
|
||||||
|
|
Loading…
Reference in a new issue