sockets - 使用 read_to_string 时如何停止在新行上?

标签 sockets tcp rust

我正在用 Rust 编写套接字服务器,并已实现响应/发送代码。主要问题是 read_to_string 方法会一直工作到连接关闭,而不是直到出现换行符。

例如,在这段代码中,

use std::net::{TcpListener, TcpStream};
use std::io::Write;
use std::io::Read;

fn handle_client(stream: TcpStream) {
    let conn = stream;
    let conn = send(conn, "Hello!");
    let mut conn = send(conn, "Bye!");
    fn send(mut stream: TcpStream, s: &str) -> TcpStream {
        let giver = format!("{}\n", s);
        let _ = stream.write(giver.into_bytes().as_slice());
        return stream;
    }
    let mut response: String = "".to_string();
    let length = conn.read_to_string(&mut response); // ignore here too
    println!("Message:\n{}\n\nLength: {}", response, length.unwrap());
}

服务器将在呈现任何数据之前等待断开连接。

我怎样才能使响应在换行符上进行解析?

最佳答案

您想读取一行,其方法称为 BufRead::read_line .您可以将实现 Read 的内容包装在 BufReader 中:

use std::io::{Write, BufRead, BufReader};
use std::net::TcpStream;

fn handle_client(mut conn: TcpStream) {
    writeln!(&mut conn, "Hello!").expect("Unable to write");
    writeln!(&mut conn, "Bye!").expect("Unable to write");

    let mut response = String::new();
    let mut conn = BufReader::new(conn);
    let length = conn.read_line(&mut response).expect("unable to read");
    println!("Message:\n{}\n\nLength: {}", response, length);
}

fn main() {}

对原代码的补充说明:

  1. 不要忽略错误。如果您想忽略错误,那么 Rust 可能不是您喜欢使用的语言。错误被设计成难以忽视。

  2. 没有理由将 stream 重新绑定(bind)到 conn,只需使其可变即可。

  3. 使用 write!writeln! 宏将格式简化为实现Read 的内容。

  4. 不要使用".to_string,只需使用String::new

  5. 没有理由两次列出response的类型(: String, = String::new()),让类型推断来处理它。

  6. 显式 return 语句不是惯用的 Rust。

关于sockets - 使用 read_to_string 时如何停止在新行上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43059102/

相关文章:

sockets - 收到[FIN, ACK]后继续使用同一个连接

windows - WIndows 7 上的高频数据监听器 TCP 过载

rust - Rust 中的 mod.rs 和嵌套模块

rust - 在 Rust 中使用工厂模式时指定生命周期

python - App Engine 套接字参数无效

Java套接字: how the server can reads multiple lines from the client

用于 TCP/IP 的 C++ 库 类似于 C# 中的 WebClient/HttpWebRequest

C++ 游戏应用程序 UDP 与 TCP

rust - 如何定义仅测试依赖项?

javascript - Socket.io 和 Nodejs : Sending response to multiple clients and change not being saved(? )