From 9bd3b34ced3427fae05dbce13d7466ebdeb4ec96 Mon Sep 17 00:00:00 2001 From: Bastian Gruber Date: Sun, 30 Apr 2023 21:41:09 +0200 Subject: [PATCH] Bug fixes --- problem_03/src/db.rs | 2 +- problem_03/src/server.rs | 10 ++++++++-- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/problem_03/src/db.rs b/problem_03/src/db.rs index 54afec3..4f587ff 100644 --- a/problem_03/src/db.rs +++ b/problem_03/src/db.rs @@ -18,7 +18,7 @@ impl Db { } pub async fn insert_user(&self, username: String) -> Result<()> { - if !username.is_empty() && username.chars().all(char::is_alphabetic) { + if !username.is_empty() && username.chars().all(char::is_alphanumeric) { self.users.write().await.push(username); Ok(()) } else { diff --git a/problem_03/src/server.rs b/problem_03/src/server.rs index 13c7002..bfb855f 100644 --- a/problem_03/src/server.rs +++ b/problem_03/src/server.rs @@ -128,8 +128,10 @@ impl Handler { let welcome = String::from("Welcome to budgetchat! What shall I call you?"); let username; + // Send the Welcome message to the connected client let _ = self.connection.write_frame(welcome).await; + // Read the answer (username) from the client if let Some(Ok(name)) = self.connection.stream.next().await { info!("Add {name} to db"); self.db.insert_user(name.clone()).await?; @@ -138,15 +140,19 @@ impl Handler { return Ok(()); } + // Broadcast the message "* USER has entered the room" let joined_message = format!("* {username} has entered the room"); let _ = self.connection .broadcast_message(BroadcastMessage::new(username.clone(), joined_message)); + + // Write back directly to the client which users are currently in the room let room_contains_message = format!( "* The room contains {}", self.db.get_room_members(username.clone()).await.join(",") ); let _ = self.connection.write_frame(room_contains_message).await; + // Connect the client to the broadcast channel let mut receiver = self.connection.broadcast.subscribe(); while !self.shutdown.is_shutdown() { @@ -154,7 +160,7 @@ impl Handler { res = self.connection.stream.next() => match res { Some(Ok(frame)) => { let _ = self.connection - .broadcast_message(BroadcastMessage::new(username.clone(), frame)); + .broadcast_message(BroadcastMessage::new(username.clone(), format!("[{username}] {frame}"))); }, Some(Err(_)) => { error!("Could not parse frame"); @@ -170,7 +176,7 @@ impl Handler { message = receiver.recv() => { info!("Message received: {:?}", message.as_ref().unwrap()); if message.as_ref().unwrap().from != username { - let _ = self.connection.write_frame(format!("[{}] {}", username, message.as_ref().unwrap().message.clone())).await; + let _ = self.connection.write_frame(message.as_ref().unwrap().message.clone()).await; } } _ = self.shutdown.recv() => {