TcpStream 在 read_to_string 上被阻止

TcpStream blocked on read_to_string

代码

我有一个客户端 (a.rs) 和一个服务器 (b.rs):

// a.rs
use std::{
    io::{Read, Write},
    net::TcpListener,
};

fn main() {
    let listener = TcpListener::bind("0.0.0.0:6400").unwrap();
    for stream in listener.incoming() {
        let mut stream = stream.unwrap();
        let mut buf = String::new();
        println!("Waiting for query...");
        stream.read_to_string(&mut buf).unwrap();
        println!("> Received query: {}", buf);

        // Compute something based on query
        let query_res = String::from("42");

        println!("Writing...");
        stream.write(query_res.as_bytes()).unwrap();

        println!("> Done");
    }
}
// b.rs
use std::{io::{Read, Write}, net::TcpStream, thread, time::Duration};

fn main() {
    let mut stream = TcpStream::connect("127.0.0.1:6400").unwrap();

    println!("Sending query...");
    stream
        .write(String::from("What is the best number?").as_bytes())
        .unwrap();
    println!("> Done");

    println!("Receiving...");
    let mut buf = String::new();
    stream.read_to_string(&mut buf).unwrap();
    println!("> Received: {}", buf);
}

它应该是什么:

航站楼 A:

$ cargo run --bin a
Waiting for query...

航站楼 B:

$ cargo run --bin b
Sending query...
> Done
Receiving...
> Received: 42

航站楼 A:

> Received query: What is the best number?
Writing...
> Done

相反,我得到了:

航站楼 A:

$ cargo run --bin a
Waiting for query...

航站楼 B:

$ cargo run --bin b
Sending query...
> Done
Receiving...

而且两个终端都被屏蔽了。为什么以及如何解决这个问题?

read_to_string 读入 String 直到 EOF,这在您从写入端关闭流之前不会发生。

你能做什么它使用 writeln!:

将查询写成一行
println!("Sending query...");
writeln!(stream, "What is the best number?").unwrap();
println!("> Done");

并创建缓冲 reader 来读取一行:

let mut stream = stream.unwrap();
let mut reader = BufReader::new(&stream);
let mut buf = String::new();
println!("Waiting for query...");
reader.read_line(&mut buf).unwrap();
println!("> Received query: {}", buf);