gpt4 book ai didi

tcp - 对 Read trait 如何为 TcpStreams 工作的误解

转载 作者:行者123 更新时间:2023-11-29 08:25:54 27 4
gpt4 key购买 nike

我的目标是从 TcpStream 中读取一些字节,以便解析每条消息中的数据并从中构建一个结构。

loop {
let mut buf: Vec<u8> = Vec::new();
let len = stream.read(&mut buf)?;
if 0 == len {
//Disconnected
}
println!("read() -> {}", len);
}

就像在 Python 中一样,我认为 stream.read() 会阻塞,直到它收到一些数据。所以我设置了一个服务器,它为每个传入连接调用上面看到的循环。然后我尝试使用 netcat 连接到服务器; netcat 成功连接到服务器并在 stream.read() 上阻塞,这是我想要的;但是只要我发送一些数据,read() 就会返回 0。我也尝试过使用 stream.read_to_end() 做一些类似的事情,但它似乎只在连接关闭时才返回。

我如何从 TcpStream 读取每条消息,知道每条消息可以有不同的、未知的大小?

最佳答案

您正被 Vec 的潜在技术问题所困扰。超过std::io::Read ,尽管在这种特殊情况下它们都相互作用。

Read的定义和文档状态:

If the return value of this method is Ok(n), then it must be guaranteed that 0 <= n <= buf.len(). A nonzero n value indicates that the buffer buf has been filled in with n bytes of data from this source. If n is 0, then it can indicate one of two scenarios:

重要部分加粗

当你定义一个新的 Vec按照您的方式,它以 的容量开始。这意味着底层切片(您将用作缓冲区)的长度为零。结果,由于必须保证 0 <= n <= buf.len()buf.len()为零,您的 read()调用立即返回并读取 0 个字节。

要“解决”这个问题,您可以将一组默认元素分配给您的 Vec ( Vec::new().resize(1024, 0) ),或者直接使用数组 ( let mut buffer:[u8; 1024] = [0; 1024] )

关于tcp - 对 Read trait 如何为 TcpStreams 工作的误解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58675405/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com