Simple server which sends the same random bytes to multiple clients

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},

async fn main() -> io::Result<()> {
    let listener = TcpListener::bind("").await?;

    let (tx, _) = broadcast::channel(16);
    let tx2 = tx.clone();

    tokio::spawn(async move {
        loop {
            tx2.send([64u8; 5]).ok();
            println!("{}", tx2.receiver_count());

    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 {
        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 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?

Don't use std::thread::sleep. Read this for more.

Thank you so much! It worked!
You are a hero

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.