gpt4 book ai didi

sockets - 在套接字上设置读取超时

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

我在 Rust 中有一个随机丢弃消息的 TCP 回显服务器。我正在尝试在客户端套接字上设置读取超时。

客户端

use std::net::TcpStream;
use std::str;
use std::io::{self, BufRead, BufReader, Write};
use std::time::Duration;
use std::net::SocketAddr;

fn main() {
let remote: SocketAddr = "127.0.0.1:8888".parse().unwrap();
let mut stream = TcpStream::connect_timeout(&remote, Duration::from_secs(1)).expect("Could not connect to server");
stream.set_read_timeout(Some(Duration::from_millis(1))).expect("Could not set a read timeout");
loop {
let mut input = String::new();
let mut buffer: Vec<u8> = Vec::new();
io::stdin().read_line(&mut input).expect("Failed to read from stdin");
stream.write(input.as_bytes()).expect("Failed to write to server");

let mut reader = BufReader::new(&stream);

reader.read_until(b'\n', &mut buffer).expect("Could not read into buffer");
print!("{}", str::from_utf8(&buffer).expect("Could not write buffer as string"));
}
}

服务器

extern crate rand;

use std::net::{TcpListener, TcpStream};
use std::thread;
use rand::{thread_rng, Rng};

use std::io::{Error, Read, Write};

fn flip() -> bool {
let choices = [true, false];
let mut rng = thread_rng();
*rng.choose(&choices).unwrap()
}

fn handle_client(mut stream: TcpStream) -> Result<(), Error> {
let mut buf = [0; 512];
loop {
let bytes_read = stream.read(&mut buf)?;
if bytes_read == 0 {
return Ok(());
}
if flip() {
return Ok(());
}
stream.write(&buf[..bytes_read])?;
}
}

fn main() {
let listener = TcpListener::bind("127.0.0.1:8888").expect("Could not bind");
for stream in listener.incoming() {
match stream {
Err(e) => eprintln!("failed: {}", e),
Ok(stream) => {
thread::spawn(move || {
handle_client(stream).unwrap_or_else(|error| eprintln!("{:?}", error));
});
}
}
}
}

set_read_timeout 调用似乎没有做任何事情;即使我将持续时间设置为 1 毫秒,客户端仍然会在服务器丢弃消息和中止连接之间等待几秒钟。

$ rustc tcp-client-timeout.rs && ./tcp-client-timeout
test
test
foo
foo
bar


thread 'main' panicked at 'Failed to write to server: Error { repr: Os { code: 32, message: "Broken pipe" } }', src/libcore/result.rs:906:4
note: Run with `RUST_BACKTRACE=1` for a backtrace.

最佳答案

The set_read_timeout call does not seem to be doing anything; the client still waits for a few seconds between the server dropping the message and aborting the connection

这不是我运行您的代码的经验。事实上,当我在 read_until 调用之后直接添加 eprintln 时,它几乎会在服务器决定断开连接时立即打印出来。事实上,问题不在于阅读,而在于写作,正如您从错误消息中看到的那样:

thread 'main' panicked at 'Failed to write to server:

我猜您不是在“等待几秒钟”,而是多次按 Enter(“bar”和紧急消息之间的空行也表明了这一点)。您的读取超时工作正常 - 问题是 you are trying to write to a socket that the other side has already closed :

if flip() {
return Ok(());
}

通过退出循环,您将完全关闭套接字。您可以在客户端检测到这一点,也可以继续服务器循环而不是退出它。

关于sockets - 在套接字上设置读取超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46920824/

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