- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我的目标是从 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/
我是一名优秀的程序员,十分优秀!