odyssey-server/src/main.rs

62 lines
1.5 KiB
Rust
Raw Normal View History

2020-10-01 12:01:03 +00:00
mod components;
2020-09-30 14:45:22 +00:00
mod config;
2020-10-01 12:01:03 +00:00
mod systems;
2020-09-30 14:45:22 +00:00
use crate::config::Settings;
2020-09-30 15:32:55 +00:00
use futures_util::StreamExt;
use log::info;
2020-10-01 13:03:55 +00:00
use shipyard::World;
2020-09-30 15:32:55 +00:00
use std::io::Error;
use tokio::net::{TcpListener, TcpStream};
2020-09-30 14:45:22 +00:00
2020-09-30 15:32:55 +00:00
#[tokio::main]
async fn main() -> Result<(), Error> {
let settings = Settings::new().unwrap();
2020-10-01 13:03:55 +00:00
// Create world
let world = World::default();
// Create workload
world.add_workload("update").build();
tokio::spawn(update_loop(world));
2020-10-01 12:01:03 +00:00
2020-09-30 15:32:55 +00:00
// Create the event loop and TCP listener we'll accept connections on.
2020-10-01 13:03:55 +00:00
tokio::spawn(listen_websocket(settings.bind)).await.unwrap();
Ok(())
}
async fn update_loop(world: World) {
loop {
world.run_workload("update");
}
}
async fn listen_websocket(bind: String) {
let try_socket = TcpListener::bind(&bind).await;
2020-09-30 15:32:55 +00:00
let mut listener = try_socket.expect("Failed to bind");
2020-10-01 13:03:55 +00:00
info!("Listening on: {}", bind);
2020-09-30 15:32:55 +00:00
while let Ok((stream, _)) = listener.accept().await {
tokio::spawn(accept_connection(stream));
2020-09-30 14:45:22 +00:00
}
2020-09-30 15:32:55 +00:00
}
async fn accept_connection(stream: TcpStream) {
let addr = stream
.peer_addr()
.expect("connected streams should have a peer address");
info!("Peer address: {}", addr);
let ws_stream = tokio_tungstenite::accept_async(stream)
.await
.expect("Error during the websocket handshake occurred");
info!("New WebSocket connection: {}", addr);
let (write, read) = ws_stream.split();
read.forward(write)
.await
.expect("Failed to forward message")
2020-09-30 14:45:22 +00:00
}