Rust TCP/JSON server implementation
This commit is contained in:
parent
7093aa4c9c
commit
f6ac3e60a9
4 changed files with 55 additions and 1 deletions
9
Cargo.lock
generated
9
Cargo.lock
generated
|
@ -5,3 +5,12 @@ version = 3
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "compiler-course"
|
name = "compiler-course"
|
||||||
version = "0.1.0"
|
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"
|
||||||
|
|
|
@ -4,3 +4,4 @@ version = "0.1.0"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
|
json = "0.12.4"
|
||||||
|
|
|
@ -1,3 +1,5 @@
|
||||||
|
mod server;
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
println!("Hello, world!");
|
server::start("::".parse().unwrap(), 3000);
|
||||||
}
|
}
|
||||||
|
|
42
src/server.rs
Normal file
42
src/server.rs
Normal 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!"),
|
||||||
|
}
|
||||||
|
}
|
Reference in a new issue