diff --git a/src/main.rs b/src/main.rs index 684952d..7cf2d1a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,6 +1,7 @@ use tokio::{ io::{AsyncBufReadExt, AsyncWriteExt, BufReader}, net::TcpListener, + sync::broadcast, }; #[tokio::main] @@ -8,10 +9,19 @@ async fn main() { // Set up a TCP listenner to listen for incoming tcp requests let listener = TcpListener::bind("127.0.0.1:8080").await.unwrap(); + // Setting up broadcast channel: A channel that will accept messages and broadcast them to everyone connected to the TCP server + // the channel accepts an i32 that is the maximum number of messages the channel can retain at any given time + let (sender, _receiver) = broadcast::channel(10); + // First loop accept all the tcp client requests loop { + // prevent the compiler error when we try to access something in a loop when it was initialized outside of the loop + let sender = sender.clone(); + + let mut receiver = sender.subscribe(); + // accept the requests - let (mut socket, _addr) = listener.accept().await.unwrap(); + let (mut socket, addr) = listener.accept().await.unwrap(); tokio::spawn(async move { // Splitting the TCP socket into read/write halves @@ -23,21 +33,27 @@ async fn main() { // second loop keeps receving input from that one client going loop { - // number of bytes read. We will truncate the buffer - let bytes_read = buffer_reader.read_line(&mut line).await.unwrap(); + tokio::select! { + result = buffer_reader.read_line(&mut line) => { + if result.unwrap() == 0{ + break; + } + // send items to the broadcast channel + sender.send((line.clone(), addr)).unwrap(); + // clear the input buffer + line.clear(); + } - // If we received no bytes then the tcp socket must have closed - if bytes_read == 0 { - break; + result = receiver.recv() => { + let (msg, other_addr) = result.unwrap(); + + if addr != other_addr { + writer.write_all(msg.as_bytes()).await.unwrap(); + } + } } - - // Does not write to every single tcp sockets that are connected - // It only writes every single bytes in the input buffer - writer.write_all(line.as_bytes()).await.unwrap(); - - // clear the input buffer - line.clear(); } }); } } +