From a04e3d3299646eb9c1c016806b7f1de046e6ea04 Mon Sep 17 00:00:00 2001 From: Norbert Morawski Date: Sat, 8 Jul 2023 02:46:45 +0200 Subject: [PATCH] adjust messege formating --- src/main.rs | 24 +++++++++++------------- 1 file changed, 11 insertions(+), 13 deletions(-) diff --git a/src/main.rs b/src/main.rs index 2690b94..936d336 100644 --- a/src/main.rs +++ b/src/main.rs @@ -41,8 +41,8 @@ async fn start_server(addr: &str) -> Result<(), Box> { // Read username from the client let mut buf = vec![0; 1024]; - socket.read(&mut buf).await?; - let username = String::from_utf8(buf.clone()).unwrap(); + let n = socket.read(&mut buf).await?; + let username = String::from_utf8_lossy(&buf[..n]).trim().to_string(); println!("Accepted connection from {}", client_addr); @@ -51,6 +51,9 @@ async fn start_server(addr: &str) -> Result<(), Box> { // Insert client into the shared HashMap clients_shared.lock().unwrap().insert(client_addr, username.clone()); + // Clone the HashMap and release the lock + let clients_map = clients_shared.lock().unwrap().clone(); + // Spawn a new task for each client connection tokio::spawn(async move { let mut buf = vec![0; 1024]; @@ -70,20 +73,15 @@ async fn start_server(addr: &str) -> Result<(), Box> { } }; - let username = clients_shared.lock().unwrap().get(&client_addr).unwrap_or(&"Unknown".to_string()).clone(); + let username = clients_map.get(&client_addr).unwrap_or(&"Unknown".to_string()).clone(); let message = String::from_utf8_lossy(&buf[..n]).to_string(); println!( - "Received message from {} ({}): {}", - username, + "Received message from ({})\n{}: {}", client_addr, + username, message ); - - if let Err(e) = socket.write_all(&buf[0..n]).await { - eprintln!("Failed to write to socket; err = {:?}", e); - return; - } } }); } @@ -98,15 +96,15 @@ async fn start_client(addr: &str) -> Result<(), Box> { std::io::stdin().read_line(&mut username)?; // Send username to the server - stream.write_all(username.as_bytes()).await?; + stream.write_all(username.trim().as_bytes()).await?; println!("Connected to server at {}", addr); let mut input = String::new(); loop { std::io::stdin().read_line(&mut input)?; - stream.write_all(input.as_bytes()).await?; + stream.write_all(input.trim().as_bytes()).await?; - // Print sent messege + // Print sent message println!("Sent message from {}: {}", username.trim(), input.trim()); input.clear(); }