2022-09-20 15:53:53 -05:00
|
|
|
use std::net::TcpListener;
|
|
|
|
use std::thread;
|
2022-09-29 15:28:38 -05:00
|
|
|
use std::sync::{Arc, Mutex};
|
2022-09-20 15:53:53 -05:00
|
|
|
|
|
|
|
use tungstenite::protocol::Message;
|
|
|
|
|
2022-09-29 15:28:38 -05:00
|
|
|
use sha2::{Sha256, Digest};
|
|
|
|
|
2022-09-20 15:53:53 -05:00
|
|
|
fn main() {
|
2022-09-29 15:28:38 -05:00
|
|
|
let code_generator = Arc::new(Mutex::new(CodeGenerator {
|
|
|
|
counter: 0,
|
|
|
|
salt: [0; 32], // TODO have this be randomized on startup
|
|
|
|
}));
|
2022-09-20 15:53:53 -05:00
|
|
|
let server = TcpListener::bind("127.0.0.1:8080").unwrap();
|
|
|
|
for stream in server.incoming() {
|
2022-09-29 15:28:38 -05:00
|
|
|
thread::spawn ( { let code_generator = Arc::clone(&code_generator); move || {
|
2022-09-20 15:53:53 -05:00
|
|
|
let mut ws = tungstenite::accept(stream.unwrap()).unwrap();
|
|
|
|
println!("New client!");
|
|
|
|
ws.write_message(Message::Text("HOSTJOIN:".to_string())).unwrap();
|
|
|
|
loop {
|
|
|
|
let message = ws.read_message();
|
|
|
|
println!("{:?}", message);
|
2022-09-29 15:28:38 -05:00
|
|
|
match message {
|
|
|
|
Err(_) => break,
|
|
|
|
Ok(Message::Text(msg)) =>
|
|
|
|
match msg.as_str().trim() {
|
|
|
|
"HOST:" => {
|
|
|
|
ws.write_message(Message::Text(code_generator.lock().unwrap().generate())).unwrap();
|
|
|
|
},
|
|
|
|
_ => unimplemented!(),
|
|
|
|
},
|
|
|
|
_ => unimplemented!(),
|
|
|
|
|
2022-09-20 15:53:53 -05:00
|
|
|
}
|
|
|
|
}
|
2022-09-29 15:28:38 -05:00
|
|
|
}});
|
2022-09-20 15:53:53 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
struct Room {
|
|
|
|
players: Vec<Player>,
|
|
|
|
}
|
|
|
|
|
|
|
|
struct Player {
|
|
|
|
name: String,
|
|
|
|
}
|
2022-09-29 15:28:38 -05:00
|
|
|
|
|
|
|
struct CodeGenerator {
|
|
|
|
counter: u64,
|
|
|
|
salt: [u8; 32],
|
|
|
|
}
|
|
|
|
|
|
|
|
impl CodeGenerator {
|
|
|
|
fn generate(&mut self) -> String {
|
|
|
|
let count = self.counter;
|
|
|
|
self.counter += 1;
|
|
|
|
|
|
|
|
let mut hasher = Sha256::new();
|
|
|
|
hasher.update(self.salt);
|
|
|
|
hasher.update(count.to_be_bytes());
|
|
|
|
|
|
|
|
format!("{:x}", hasher.finalize())[..6].to_string()
|
|
|
|
}
|
|
|
|
}
|