1
0
Fork 0

Rust TCP/JSON server implementation

This commit is contained in:
Vili Sinervä 2025-01-18 12:51:26 +02:00
parent 7093aa4c9c
commit f6ac3e60a9
No known key found for this signature in database
GPG key ID: DF8FEAF54EFAC996
4 changed files with 55 additions and 1 deletions

9
Cargo.lock generated
View file

@ -5,3 +5,12 @@ version = 3
[[package]]
name = "compiler-course"
version = "0.1.0"
dependencies = [
"json",
]
[[package]]
name = "json"
version = "0.12.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "078e285eafdfb6c4b434e0d31e8cfcb5115b651496faca5749b88fafd4f23bfd"

View file

@ -4,3 +4,4 @@ version = "0.1.0"
edition = "2021"
[dependencies]
json = "0.12.4"

View file

@ -1,3 +1,5 @@
mod server;
fn main() {
println!("Hello, world!");
server::start("::".parse().unwrap(), 3000);
}

42
src/server.rs Normal file
View file

@ -0,0 +1,42 @@
use json;
use std::{
io::prelude::*,
net::{IpAddr, TcpListener, TcpStream},
thread,
};
pub fn start(address: IpAddr, port: u16) {
let address_string = format!("{address}:{port}");
let listener = TcpListener::bind(&address_string).unwrap_or_else(|error| {
panic!("Problem starting listener: {error:?}");
});
println!("Listening for connections on {address_string}");
for stream in listener.incoming() {
let stream = stream.unwrap();
thread::spawn(|| {
handle_connection(stream);
});
}
}
fn handle_connection(mut stream: TcpStream) {
let mut buffer = String::new();
stream
.read_to_string(&mut buffer)
.expect("Unable to read from buffer!");
let json_request = json::parse(&buffer).expect("Malformed JSON!");
match json_request["command"].as_str().unwrap() {
"ping" => println!("ping"),
"compile" => {
let program = &json_request["code"].as_str().unwrap();
println!("compile code:\n\n{program}\n");
}
_ => panic!("Unexpected command!"),
}
}