gpt4 book ai didi

rust - UnixStream 写入/读取完整字符串

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

我有一个问题的这个小示例版本:

#[test]
fn streams() {
use std::io::prelude::*;
use std::net::Shutdown;
use std::os::unix::net::UnixStream;
use std::time::Duration;

let (mut s1, mut s2) = UnixStream::pair().unwrap();
s1.write_all(b"hello world").unwrap();
// Problem is that if not calling shutdown message never arrives
s1.shutdown(Shutdown::Write).unwrap();
let mut response = String::new();
s2.read_to_string(&mut response).unwrap();
assert_eq!("hello world".to_string(), response);
}

Playground link

我需要关闭连接,否则消息永远不会到达。我认为问题在于 write_all 不写入 EOF,因此在使用 read_to_string 时挂起。

例如在 python 中我会简单地使用:

socket.sendall(message.encode())
data = socket.recv(1024)

发送和接收回复。

我怎样才能用 Rust 实现同样的效果?

提前谢谢你。

最佳答案

read_to_string的语义是:

Read all bytes until EOF in this source, appending them to buf.

If successful, this function returns the number of bytes which were read and appended to buf.

所以如果你不关闭流它就会挂起。您想改用 read:

    let (mut s1, mut s2) = UnixStream::pair().unwrap();
s1.write_all(b"hello world").unwrap();
let mut buf = [0; 1024];
let count = s2.read(&mut buf).unwrap();
let response = String::from_utf8(buf[..count].to_vec()).unwrap();
assert_eq!("hello world".to_string(), response);

关于rust - UnixStream 写入/读取完整字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57646423/

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