rewrite std::sync Mutex to tokio
This commit is contained in:
parent
a04e3d3299
commit
57b35902ae
@ -2,9 +2,10 @@ use std::collections::HashMap;
|
||||
use std::env;
|
||||
use std::error::Error;
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::sync::Arc;
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::{TcpListener, TcpStream};
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn Error>> {
|
||||
@ -49,10 +50,10 @@ async fn start_server(addr: &str) -> Result<(), Box<dyn Error>> {
|
||||
let clients_shared = Arc::clone(&clients);
|
||||
|
||||
// Insert client into the shared HashMap
|
||||
clients_shared.lock().unwrap().insert(client_addr, username.clone());
|
||||
clients_shared.lock().await.insert(client_addr, username.clone());
|
||||
|
||||
// Clone the HashMap and release the lock
|
||||
let clients_map = clients_shared.lock().unwrap().clone();
|
||||
let clients_map = clients_shared.lock().await.clone();
|
||||
|
||||
// Spawn a new task for each client connection
|
||||
tokio::spawn(async move {
|
||||
@ -62,7 +63,7 @@ async fn start_server(addr: &str) -> Result<(), Box<dyn Error>> {
|
||||
let n = match socket.read(&mut buf).await {
|
||||
Ok(n) if n == 0 => {
|
||||
// Client disconnected
|
||||
let username = clients_shared.lock().unwrap().remove(&client_addr).unwrap_or("Unknown".to_string());
|
||||
let username = clients_shared.lock().await.remove(&client_addr).unwrap_or("Unknown".to_string());
|
||||
println!("Client {} ({}) disconnected!", username, client_addr);
|
||||
return;
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user