0

我正在尝试使用 tokio 从套接字读取数据。数据是 Picamera 发送的字节,我从代码中读取并写入文件。当我运行文件时,似乎中间丢失了一些片段。上面的代码是:

let listener = TcpListener::bind("0.0.0.0:8080").await?;
    println!("Server started listening");
    loop {
        let (mut socket, _) = listener.accept().await?;

        tokio::spawn(async move {
            let mut buf = [0; 1024];
            let f = File::create("./test.h264").expect("Unable to create file");
            let mut f = BufWriter::new(f);
            // In a loop, read data from the socket and write the data back.
            loop {
                let n = match socket.read(&mut buf).await {
                    // socket closed
                    Ok(n) if n == 0 => return,
                    Ok(n) => {
                        f.write_all(&buf[0..n]).expect("Write failed");
                        n
                    },
                    Err(e) => {
                        eprintln!("failed to read from socket; err = {:?}", e);
                        return;
                    }
                };

                // Write the data back
                // if let Err(e) = socket.write_all(&buf[0..n]).await {
                //     eprintln!("failed to write to socket; err = {:?}", e);
                //     return;
                // }
            }
        });
    }

我无法弄清楚发生了什么。我想我已经指定了大小为 1024 的窃听器,当它在写入文件时读取 1024 时,一些数据包在再次开始读取之前丢失了。我可能错了。我想保持从我的 pi 捕获的恒定视频流。提前感谢您的帮助。

4

0 回答 0