hexland-server/src/main.rs
2022-10-04 16:59:12 -05:00

73 lines
2.0 KiB
Rust

use std::{
sync::{Arc, Mutex},
io::Error as IoError,
collections::HashMap,
};
use tokio::net::{TcpListener};
mod message;
use message::{Message, MessageWebSocket};
mod code_generator;
use code_generator::CodeGenerator;
#[tokio::main]
async fn main() -> Result<(), IoError> {
let global_state = Arc::new(GlobalState::default());
let socket = TcpListener::bind("127.0.0.1:8080").await;
let listener = socket.expect("Could not bind to localhost:8080");
println!("Server running");
while let Ok((stream, addr)) = listener.accept().await {
let global_state = Arc::clone(&global_state);
let mut local_state = LocalState::default();
tokio::spawn(async move {
// Upgrade to a WS connection
let mut ws = MessageWebSocket(tokio_tungstenite::accept_async(stream)
.await
.expect("Could not establish connection"));
println!("Connected to {}", addr);
while let Ok(msg) = ws.next().await {
dispatch(msg, &global_state, &mut local_state, &mut ws).await;
}
});
}
Ok(())
}
async fn dispatch(
msg: Message,
global_state: &GlobalState,
local_state: &mut LocalState,
ws: &mut MessageWebSocket
) {
match msg.command.as_str() {
"HOST" => {
let room_code = global_state.code_generator.lock().unwrap().generate();
let game_controller = GameController::default();
global_state.rooms.lock().unwrap().insert(room_code, game_controller);
}
"JOIN" => {
let room_code = &msg.args[0];
let room = global_state.rooms.lock().unwrap().get(room_code);
}
_ => unimplemented!(),
}
}
#[derive(Default)]
struct GlobalState {
code_generator: Arc<Mutex<CodeGenerator>>,
rooms: Arc<Mutex<HashMap<String, GameController>>>,
}
#[derive(Default)]
struct GameController {} // TODO
#[derive(Default)]
struct LocalState {
}