sonet_rs/
server.rs

1use std::net::SocketAddr;
2use std::sync::Arc;
3use tokio::net::TcpListener;
4use tokio::sync::Mutex;
5use crate::client::{Client, Connection};
6use crate::packet::PacketRegistry;
7use crate::serializer::Codec;
8
9/// The SonetServer struct
10pub struct SonetServer {
11    pub socket_address: SocketAddr,
12    pub client_handlers: Vec<Box<dyn Fn(&mut Client)>>
13}
14
15/// The Default Implementation
16impl SonetServer {
17    /// New SonetServer Future. Requires Asynchronous runtime
18    pub async fn new(port: i32) -> Result<SonetServer, std::io::Error> {
19        let socket_address = format!("127.0.0.1:{}", port).parse::<SocketAddr>().expect("Failed to bind port to address");
20        Ok(SonetServer {
21            socket_address,
22            client_handlers: vec![]
23        })
24    }
25
26    /// Starts the server. This requires the asynchronous runtime
27    pub async fn start(&self, registry: PacketRegistry) -> Result<(), std::io::Error> {
28        let codec = Arc::new(Mutex::new(Codec::new(registry)));
29
30        let socket = TcpListener::bind(self.socket_address).await?;
31
32        loop {
33            let (socket, _) = socket.accept().await?;
34
35             let mut client = Client {
36                connection: Connection {
37                    socket,
38                    codec: codec.clone(),
39                },
40                packet_handlers: Arc::new(Mutex::new(vec![]))
41            };
42
43            for handler in self.client_handlers.iter() {
44                handler(&mut client);
45            }
46
47            Box::leak(Box::new(client)).initialize().await?; // STOP BLOCKING! 
48        }
49    }
50
51    pub fn add_client_handler<T>(&mut self, closure: T) where T: Fn(&mut Client) + 'static {
52        self.client_handlers.push(Box::new(closure));
53    }
54
55    pub fn stop(&mut self) {}
56}