This commit is contained in:
Crispy 2022-06-04 19:22:41 +02:00
commit 9f01e334e1
4 changed files with 54 additions and 0 deletions

1
.gitignore vendored Normal file
View file

@ -0,0 +1 @@
/target

7
Cargo.lock generated Normal file
View file

@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "webserver"
version = "0.1.0"

8
Cargo.toml Normal file
View file

@ -0,0 +1,8 @@
[package]
name = "webserver"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

38
src/main.rs Normal file
View file

@ -0,0 +1,38 @@
use std::{net::{TcpStream, TcpListener}, io::prelude::*, fs};
fn main() {
let listener = TcpListener::bind("192.168.0.108:25585").unwrap();
for stream in listener.incoming() {
let stream = stream.unwrap();
println!("IP: {}\n", stream.peer_addr().unwrap());
handle_connection(stream);
}
}
fn handle_connection(mut stream: TcpStream) {
let mut buffer = vec![0; 1024];
let size = stream.read(&mut buffer).unwrap();
buffer.resize(size, 0);
let contents = fs::read_to_string("src/main.rs").unwrap();
let response = format!(
"HTTP/1.1 200 OK\nContent-Length: {}\n\n{}",
contents.len() + buffer.len(),
contents
);
stream.write(response.as_bytes()).unwrap();
stream.write(&buffer).unwrap();
stream.flush().unwrap();
println!("read {} bytes:\n{}", size,
String::from_utf8_lossy(&buffer)
.escape_debug()
.collect::<String>()
.replace("\\r\\n", "\n")
.replace("\\n", "\n")
);
}