如何将字节向量流式传输到 BufWriter?

Posted

技术标签:

【中文标题】如何将字节向量流式传输到 BufWriter?【英文标题】:How to stream a vector of bytes to BufWriter? 【发布时间】:2022-01-20 17:34:38 【问题描述】:

我正在尝试使用 io::copy(&mut reader, &mut writer) 将字节流式传输到 tcp 服务器,但它给了我这个错误:the trait "std::io::Read" is not implemented for "Vec<integer>"。在这里,我有一个字节向量,这与我打开文件并将其转换为字节相同。我想将字节写入BufWriter。我做错了什么?

use std::io;
use std::net::TcpStream;
use std::io::BufWriter;

pub fn connect() 
    if let Ok(stream) = TcpStream::connect("localhost:8080") 
        println!("Connection established!");
        let mut reader = vec![
            137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 70, 0, 0, 0, 70,
        ];
        let mut writer = BufWriter::new(&stream);
        io::copy(&mut reader, &mut writer).expect("Failed to write to stream");
     else 
        println!("Couldn't connect to the server")
    

error[E0277]: the trait bound `Vec<integer>: std::io::Read` is not satisfied
  --> src/lib.rs:12:31
   |
12 |         io::copy(&mut reader, &mut writer).expect("Failed to write to stream");
   |         --------              ^^^^^^^^^^^ the trait `std::io::Read` is not implemented for `Vec<integer>`
   |         |
   |         required by a bound introduced by this call
   |
note: required by a bound in `std::io::copy`

【问题讨论】:

【参考方案1】:

像这样使用.as_slice() 对我有用:

pub fn connect() 
    if let Ok(stream) = TcpStream::connect("localhost:8080") 
        println!("Connection established!");
        let reader = vec![
            137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 70, 0, 0, 0, 70,
        ];
        let mut writer = BufWriter::new(&stream);
        io::copy(&mut reader.as_slice(), &mut writer).expect("Failed to write to stream");
     else 
        println!("Couldn't connect to the server")
    

那是因为std::io::Read 支持切片。

【讨论】:

【参考方案2】:

这里编译器有点麻烦,Vec 没有实现 Read&amp;[u8] 实现了,在创建可变引用之前,您只需从 vec 获取一个 slice:

copy(&mut reader.as_slice(), &mut writer).expect("Failed to write to stream");

另见:

What is the difference between storing a Vec vs a Slice? What are the differences between Rust's `String` and `str`?

【讨论】:

好的,切片是什么? 现在服务器出现紧急情况:thread "main" panicked at "called "Result::unwrap()" on an "Err" value: Error kind: InvalidData, message: "stream did not contain valid UTF-8" "。是否可以将字节流式传输到 tcp 服务器? @Nicke7117 您发送的另一个问题我无法真正帮助您 @Nicke7117 最好将您的服务器恐慌作为一个单独的问题询问。 @Nicke7117 “什么是切片?” → doc.rust-lang.org/reference/types/slice.html 和 doc.rust-lang.org/std/primitive.slice.html

以上是关于如何将字节向量流式传输到 BufWriter?的主要内容,如果未能解决你的问题,请参考以下文章

如何将对象流式传输到压缩的 json?

将视频文件作为字节流式传输到stdin

如何将 Django 3 中的 mp4 视频流式传输到 Vue.js

如何使用集合元素重用向量?

如何将 jpeg 帧从 java 客户端流式传输到 python 服务器

通过 AvPlayerItem 和 AvPlayer 流式传输时监控下载的字节数 - iOS