Hi Rust community!
This is my first post here and I'd really appreciate your help.
I wrote the following code to produce a simple TCP server which listens to incoming connections and sends the same random bytes to all the clients (I left the random part out to keep my example simple).
I thought I'd use one thread to create the random bytes and one thread for each connected client.
use std::{thread, time::Duration};
use tokio::{
io::{self, AsyncWriteExt},
net::{TcpListener, TcpStream},
sync::broadcast::{self, Receiver},
};
#[tokio::main]
async fn main() -> io::Result<()> {
let listener = TcpListener::bind("0.0.0.0:8080").await?;
let (tx, _) = broadcast::channel(16);
let tx2 = tx.clone();
tokio::spawn(async move {
loop {
// IMAGINE RANDOM BYTES
tx2.send([64u8; 5]).ok();
println!("{}", tx2.receiver_count());
thread::sleep(Duration::from_millis(1500));
}
});
loop {
let (client, _) = listener.accept().await?;
let rx = tx.subscribe();
process_client(client, rx).await;
}
}
async fn process_client(mut client: TcpStream, mut receiver: Receiver<[u8; 5]>) {
tokio::spawn(async move {
println!("Connected");
while let Ok(received) = receiver.recv().await {
let res = client.write(&received).await;
println!("{:?}", res);
}
});
}
When I connect to the server (e.g. via netcat nc 127.0.0.1 8080
) it shows the updated count of clients in the logs, however the while
loop inside process_client
which listens to the broadcast queue is not triggered.
Do you have any ideas why this is failing?