use std::{error::Error, net::SocketAddr, sync::Arc}; use connection::{connection_worker, Connections, RawConnection, UnestablishedConnection}; use listener::Listeners; use tokio::{ io::{AsyncRead, AsyncWrite}, net::{TcpListener, TcpStream}, sync::Mutex, }; use tokio_tungstenite::{accept_async, WebSocketStream}; pub mod command; pub mod connection; pub mod handshake; pub mod listener; pub mod model; #[macro_use] extern crate tracing; #[tokio::main] async fn main() -> Result<(), Box> { let mut listener = TcpListener::bind("127.0.0.1:8080").await?; let mut connections: Arc> = Arc::default(); let mut listeners: Arc> = Arc::default(); loop { let stream = accept_stream(&mut listener).await; let (stream, address) = match stream { Ok(stream) => stream, Err(err) => { error!("Failed to accept connection. {:?}", err); continue; } }; let connection = accept_websocket_connection(stream).await; let connection = match connection { Ok(connection) => connection, Err(err) => { error!( "Failed to initiate Websocket connection from {}. {:?}", address, err ); continue; } }; let connection = RawConnection { task: tokio::spawn(connection_worker( connection, listeners.clone(), connections.clone(), address, )), }; connections.lock().await.connections.push(connection); } } async fn accept_stream( listener: &mut TcpListener, ) -> Result<(TcpStream, SocketAddr), Box> { let stream = listener.accept().await?; Ok(stream) } async fn accept_websocket_connection( stream: S, ) -> Result, Box> { let connection = accept_async(stream).await?; Ok(connection) }