From 87a669f8991de3373be598ee0bc10ecf155c6749 Mon Sep 17 00:00:00 2001 From: Marc Planard Date: Fri, 25 Aug 2023 20:47:24 +0200 Subject: [PATCH] refactoring --- pub/index.html | 4 ++++ pub/main.js | 19 +++++++++++---- pub/style.css | 17 ++++++++++++++ src/gen_server.rs | 3 +-- src/main.rs | 7 ++---- src/ws_client.rs | 60 +++++++++++++++++++++++------------------------ 6 files changed, 68 insertions(+), 42 deletions(-) diff --git a/pub/index.html b/pub/index.html index 8446511..41ae32d 100644 --- a/pub/index.html +++ b/pub/index.html @@ -20,6 +20,10 @@ LJ Sketch + + + + diff --git a/pub/main.js b/pub/main.js index c055ffc..511594d 100644 --- a/pub/main.js +++ b/pub/main.js @@ -108,13 +108,22 @@ const initDrawing = (canvas, clearButton, selectedColor, ws) => { }); }; - -const initWs = () => { +const initWs = errorBox => { const socket = new WebSocket('ws://localhost:3000/ws'); socket.addEventListener('open', function (event) { + console.log("Open", event); + }); + socket.addEventListener('error', function (event) { + console.log("Error:", event); + errorBox.className = "visible"; + errorBox.innerHTML = "Error: " + event.message; + }); + socket.addEventListener("close", (event) => { + console.log("Close:", event); + errorBox.className = "visible"; + errorBox.innerHTML = "Disconnected: server closed connexion"; }); - return socket; }; @@ -122,9 +131,9 @@ window.onload = () => { const colorsDiv = document.querySelector("#colors"); const selectedColor = document.querySelector("#selectedColor"); const clearButton = document.querySelector("#clearButton"); + const errorBox = document.querySelector("#errorBox"); const canvas = document.querySelector("#canvas"); initUI(colorsDiv, selectedColor); - let ws = initWs(); + let ws = initWs(errorBox); initDrawing(canvas, clearButton, selectedColor, ws); - }; diff --git a/pub/style.css b/pub/style.css index 0ad422d..cd38883 100644 --- a/pub/style.css +++ b/pub/style.css @@ -64,3 +64,20 @@ body { text-align: center; } +#errorBox { + border: thick solid #990000; + background: #dd0000; + position: fixed; + bottom: 0px; + right: 0px; + text-align: center; + padding: 1em; + font-size: x-large; +} + +.visible { + display: block; +} +.invisible { + display: none; +} diff --git a/src/gen_server.rs b/src/gen_server.rs index 38e336d..758321b 100644 --- a/src/gen_server.rs +++ b/src/gen_server.rs @@ -25,8 +25,7 @@ async fn gen_server(mut rx: Receiver) { match msg { GSMsg::NewClient((addr, c_tx)) => { for line in &lines { - c_tx.send(GSMsg::NewLine(line.clone())) - .await.unwrap(); + c_tx.send(GSMsg::NewLine(line.clone())).await.unwrap(); } clients.insert(addr, c_tx); tracing::info!("NewClient {addr}"); diff --git a/src/main.rs b/src/main.rs index 3dbbbcc..cb957cc 100644 --- a/src/main.rs +++ b/src/main.rs @@ -27,11 +27,8 @@ const LISTEN_ON : &str = "0.0.0.0:3000"; #[tokio::main] async fn main() { tracing_subscriber::registry() - .with( - tracing_subscriber::EnvFilter::try_from_default_env() - .unwrap_or_else(|_| "lj_sketch=info,tower_http=info" - .into()), - ) + .with(tracing_subscriber::EnvFilter::try_from_default_env() + .unwrap_or_else(|_| "lj_sketch=info,tower_http=info".into())) .with(tracing_subscriber::fmt::layer()) .init(); diff --git a/src/ws_client.rs b/src/ws_client.rs index 93a677a..adc32a2 100644 --- a/src/ws_client.rs +++ b/src/ws_client.rs @@ -1,10 +1,10 @@ -use axum::extract::ws::{ Message, Message::Text, Message::Close, WebSocket }; +use axum::extract::ws::{Message, Message::Text, Message::Close, WebSocket}; use std::net::SocketAddr; use tokio::sync::mpsc::{self, Sender}; -use serde::{Serialize,Deserialize}; -use core::ops::ControlFlow; +use serde::{Serialize, Deserialize}; +use core::ops::ControlFlow; use crate::gen_server::GSMsg; -use crate::line::{Line,simplify_line}; +use crate::line::{Line, simplify_line}; #[derive(Serialize, Deserialize, Debug)] #[serde(tag = "t")] @@ -26,8 +26,8 @@ pub async fn handle_socket( who: SocketAddr, gs_tx: Sender ) { - let (c_tx, mut c_rx) = mpsc::channel(32); - gs_tx.send(GSMsg::NewClient((who, c_tx))).await.unwrap(); + let (chan_tx, mut chan_rx) = mpsc::channel(32); + gs_tx.send(GSMsg::NewClient((who, chan_tx))).await.unwrap(); let mut line : Line = vec![]; loop { @@ -42,7 +42,7 @@ pub async fn handle_socket( ControlFlow::Continue(()) => {} } }, - Some(msg) = c_rx.recv() => { + Some(msg) = chan_rx.recv() => { process_gs_msg(&mut socket, &who, msg).await }, else => { @@ -53,7 +53,11 @@ pub async fn handle_socket( } } -async fn process_gs_msg(socket: &mut WebSocket, who: &SocketAddr, msg: GSMsg) { +async fn process_gs_msg( + socket: &mut WebSocket, + who: &SocketAddr, + msg: GSMsg +) { match msg { GSMsg::NewLine(line) => { socket.send(Message::Text(line_to_json(&line))).await.unwrap(); @@ -75,32 +79,30 @@ async fn process_ws_msg( msg: Message ) -> ControlFlow<(),()> { match msg { - Text(text) => { - match serde_json::from_str(&text) { - Ok(json) => { - tracing::debug!("{who}: '{:?}'", json); - match handle_ws_msg(line, json) { - Ok(Some(req)) => gs_tx.send(req).await.unwrap(), - Ok(None) => {}, - Err(err) => { - tracing::warn!("{who}: message error: {err}"); - } + Text(text) => match serde_json::from_str(&text) { + Ok(json) => { + tracing::debug!("{who}: '{json:?}'"); + match handle_ws_msg(line, json) { + Ok(Some(req)) => gs_tx.send(req).await.unwrap(), + Ok(None) => {}, + Err(err) => { + tracing::warn!("{who}: message error: {err}"); } - }, - Err(err) => { - tracing::warn!("{who}: can't parse JSON: {err}"); } + }, + Err(err) => { + tracing::warn!("{who}: can't parse JSON: {err}"); } }, Close(close) => { - tracing::info!("{who}: closing: {:?}", close); + tracing::info!("{who}: closing: {close:?}"); gs_tx.send(GSMsg::DeleteClient(*who)).await.unwrap(); return ControlFlow::Break(()); }, _ => { - tracing::warn!("{who}: can't handle message: {:?}", msg); + tracing::warn!("{who}: can't handle message: {msg:?}"); } - } + }; ControlFlow::Continue(()) } @@ -121,13 +123,13 @@ fn handle_ws_msg( }, JMsg::Stroke => { if line.len() > 1 { - let line2 = simplify_line(line); + let simple_line = simplify_line(line); *line = vec![]; - return Ok(Some(GSMsg::NewLine(line2))); + return Ok(Some(GSMsg::NewLine(simple_line))); } }, JMsg::Line{..} => { - tracing::warn!("recieved a line message O_o"); + return Err("recieved a line message O_o"); } }; Ok(None) @@ -135,9 +137,7 @@ fn handle_ws_msg( fn line_to_json(line: &Line) -> String { let line = line.iter() - .map(| (x, y, c) | { - (*x, *y, format!("#{:06x}", c)) - }) + .map(| (x, y, c) | (*x, *y, format!("#{:06x}", c))) .collect(); serde_json::to_string(&JMsg::Line{ line }).unwrap() }