From f3405890721b5092d60cd7a470e3711c4b86e204 Mon Sep 17 00:00:00 2001 From: metamuffin Date: Sun, 16 Jun 2024 21:58:21 +0200 Subject: stuff --- src/main.rs | 63 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 src/main.rs (limited to 'src/main.rs') diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 00000000..f688cffe --- /dev/null +++ b/src/main.rs @@ -0,0 +1,63 @@ +use anyhow::Result; +use game::Game; +use log::info; +use protocol::{PacketC, PacketS}; +use std::{sync::Arc, time::Duration}; +use tokio::{ + io::{AsyncBufReadExt, AsyncWriteExt, BufReader}, + net::TcpListener, + spawn, + sync::{broadcast, RwLock}, + time::sleep, +}; + +pub mod game; +pub mod protocol; + +#[tokio::main] +async fn main() -> Result<()> { + env_logger::init_from_env("LOG"); + let listener = TcpListener::bind("0.0.0.0:27031").await?; + info!("listening on {}", listener.local_addr()?); + + let game = Arc::new(RwLock::new(Game::new())); + let (tx, rx) = broadcast::channel::(1024); + + { + let game = game.clone(); + spawn(async move { + { + let mut g = game.write().await; + while let Some(p) = g.packet_out() { + let _ = tx.send(p); + } + } + sleep(Duration::from_millis(10)).await; + }); + } + + for id in 0.. { + let (sock, addr) = listener.accept().await?; + let (read, mut write) = sock.into_split(); + let game = game.clone(); + let mut rx = rx.resubscribe(); + info!("{addr} connected"); + spawn(async move { + while let Ok(packet) = rx.recv().await { + write + .write_all(serde_json::to_string(&packet).unwrap().as_bytes()) + .await + .unwrap(); + } + }); + spawn(async move { + let mut read = BufReader::new(read).lines(); + while let Ok(Some(line)) = read.next_line().await { + let packet: PacketS = serde_json::from_str(&line).unwrap(); + game.write().await.packet_in(id, packet).unwrap(); + } + }); + } + + Ok(()) +} -- cgit v1.2.3-70-g09d2