use std::io::{BufRead, BufReader, Write};
use std::net::{TcpListener, TcpStream};
use std::sync::{Arc, Mutex};
use std::thread;
fn handle_client(stream: TcpStream, clients: Arc<Mutex<Vec<TcpStream>>>) {
let mut reader = BufReader::new(stream.try_clone().unwrap());
loop {
let mut msg = String::new();
let bytes_read = reader.read_line(&mut msg).unwrap();
if bytes_read == 0 {
break; }
println!("Received: {}", msg.trim_end());
let clients_guard = clients.lock().unwrap();
for mut client in clients_guard.iter() {
let _ = client.write_all(msg.as_bytes());
}
}
}
fn main() -> std::io::Result<()> {
let listener = TcpListener::bind("0.0.0.0:4000")?;
println!("Chat server listening on 0.0.0.0:4000");
let clients = Arc::new(Mutex::new(Vec::new()));
for stream in listener.incoming() {
match stream {
Ok(stream) => {
let mut clients_guard = clients.lock().unwrap();
clients_guard.push(stream.try_clone().unwrap());
let clients_clone = Arc::clone(&clients);
thread::spawn(move || handle_client(stream, clients_clone));
}
Err(e) => eprintln!("Connection failed: {}", e),
}
}
Ok(())
}