You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rust如何向多客户端持续发送字节流并解决TCP广播队列满问题

更新

我使用TCP作为通信方式取得了一定进展,但还未完全实现目标。我已经解决了下方列出的大部分问题,但是也出现了新的问题。
我的实现思路为:开启独立线程生成随机数并将其写入消息队列,客户端连接时同样使用独立线程处理,理想状态下所有客户端都能从广播队列获取到完全相同的随机数。

目前该实现运行顺畅,直到队列缓冲区被占满为止,队列满后就无法再写入新的消息。我还没找到移除队列中已发送消息的方法,希望有人能帮忙解决。

备注:我已经尝试过很多广播相关的crates,但是始终没有成功运行。

Cargo.toml

[dependencies]
ring = { version = "0.16.20" }
multiqueue = { version ="0.3.2" }

main.rs

use core::time;
use multiqueue;
use ring::rand::{SecureRandom, SystemRandom};
use std::io::prelude::*;
use std::{net::TcpListener, thread};

const RND_SIZE: usize = 1024;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let (tx, rx) = multiqueue::broadcast_queue(32);

    let sr = SystemRandom::new();
    let mut randoms: [u8; RND_SIZE] = [0; RND_SIZE];

    let socket = TcpListener::bind("127.0.0.1:8080")?;

    thread::spawn(move || loop {
        // RNG
        sr.fill(&mut randoms).unwrap();

        // Random bytes into broadcasting queue
        tx.try_send(randoms).ok();

        let sleep_duration = time::Duration::from_millis(100);
        thread::sleep(sleep_duration);
    });

    // Handle different client connections
    for stream in socket.incoming() {
        match stream {
            Ok(mut stream) => {
                // Adding a separate stream to the queue which is owned by the thread below
                let rx = rx.add_stream();
                thread::spawn(move || {
                    let mut i = 0;
                    for received in rx {
                        println!("Sending {:?}", i);
                        i = i + 1;
                        // Sending bytes to the connected client
                        stream.write_all(&received).ok();
                    }
                });
            }
            Err(_) => {}
        }
    }
    Ok(())
}

初始问题

首先我是Rust新手,我想要用Rust实现一个可以向多个客户端持续流式传输随机字节的简易服务器,高吞吐量是核心要求。客户端需要支持订阅和退订流,且所有客户端必须收到完全相同的随机字节,因此需要实现带标识的分块传输逻辑。

原始代码因篇幅过长已移除

内容的提问来源于stack exchange,提问作者3v3ryb0dy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 18:18:05