gpt4 book ai didi

rust - 如何防止 TcpStream 阻塞读取?

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

let listener = TcpListener::bind("localhost:1234").unwrap();
for stream in listener.incoming() {
let s = stream.unwrap();
handle_stream(s);
}

fn handle_stream(mut stream: TcpStream) -> () {
let mut buf = [0];
loop {
let _ = match stream.read(&mut buf) {
Err(e) => panic!("Got an error: {}", e),
Ok(m) => {
println!("Received {:?}, {:?}", m, buf);
if m == 0 {
// doesn't reach here.
break;
}
m
},
};
}
}

然后我通过运行 curl http://localhost:1234 连接到服务器。

我希望 Ok(0) 会被返回,但它没有到达该语句而是挂起。如果那是 EOF,我该如何处理这种情况?

最佳答案

您想使用 TcpStream::set_read_timeout然后检查特定类型的错误:

use std::io::{self, Read};
use std::net::{TcpListener, TcpStream};
use std::time::Duration;

fn main() {
let listener = TcpListener::bind("localhost:1234").unwrap();
for stream in listener.incoming() {
let s = stream.unwrap();
handle_stream(s);
}

fn handle_stream(mut stream: TcpStream) -> () {
let mut buf = [0];
stream.set_read_timeout(Some(Duration::from_millis(100))).unwrap();
loop {
let _ = match stream.read(&mut buf) {
Err(e) => {
match e.kind() {
io::ErrorKind::WouldBlock => {
println!("would have blocked");
break;
},
_ => panic!("Got an error: {}", e),
}
},
Ok(m) => {
println!("Received {:?}, {:?}", m, buf);
if m == 0 {
// doesn't reach here.
break;
}
m
},
};
}
}
}

关于rust - 如何防止 TcpStream 阻塞读取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33557375/

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