From 5ca8dd4c842ee681ce81a6a7bbd5005cd5b98d3c Mon Sep 17 00:00:00 2001 From: Ilion Beyst Date: Mon, 27 Dec 2021 22:18:46 +0100 Subject: add websocket stub --- planetwars-cli/src/web/mod.rs | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) (limited to 'planetwars-cli/src/web') diff --git a/planetwars-cli/src/web/mod.rs b/planetwars-cli/src/web/mod.rs index 66d4218..8394897 100644 --- a/planetwars-cli/src/web/mod.rs +++ b/planetwars-cli/src/web/mod.rs @@ -1,6 +1,6 @@ use axum::{ body::{boxed, Full}, - extract::{Extension, Path}, + extract::{ws::WebSocket, Extension, Path, WebSocketUpgrade}, handler::Handler, http::{header, StatusCode, Uri}, response::{IntoResponse, Response}, @@ -36,6 +36,7 @@ pub async fn run(workspace_root: PathBuf) { // build our application with a route let app = Router::new() .route("/", get(index_handler)) + .route("/ws", get(ws_handler)) .route("/api/matches", get(list_matches)) .route("/api/matches/:match_id", get(get_match)) .fallback(static_handler.into_service()) @@ -50,6 +51,26 @@ pub async fn run(workspace_root: PathBuf) { .unwrap(); } +async fn ws_handler(ws: WebSocketUpgrade) -> impl IntoResponse { + ws.on_upgrade(handle_socket) +} + +async fn handle_socket(mut socket: WebSocket) { + while let Some(msg) = socket.recv().await { + let msg = if let Ok(msg) = msg { + msg + } else { + // client disconnected + return; + }; + + if socket.send(msg).await.is_err() { + // client disconnected + return; + } + } +} + #[derive(Serialize, Deserialize)] struct MatchData { name: String, -- cgit v1.2.3