adjust messege formating

This commit is contained in:
Norbert Morawski 2023-07-08 02:46:45 +02:00
parent 4110207303
commit a04e3d3299

View File

@ -41,8 +41,8 @@ async fn start_server(addr: &str) -> Result<(), Box<dyn Error>> {
// 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<dyn Error>> {
// 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<dyn Error>> {
}
};
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<dyn Error>> {
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();
}