BufWriter :: write()不会将字节写入TcpStream

时间:2018-08-05 07:07:37

标签: tcp rust

我已经在Rust中编写了一个回显服务器和客户端。这是我的代码:

服务器:

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

fn handle_connection(stream: TcpStream) {
    let stream_clone = stream.try_clone().unwrap();
    let mut reader = BufReader::new(stream);
    let mut writer = BufWriter::new(stream_clone);
    loop {
        let mut s = String::new();
        reader.read_line(&mut s).unwrap();
        writer.write(s.as_bytes()).unwrap();
    }
}

fn main() {
    let listener = TcpListener::bind("127.0.0.1:8888")
        .unwrap();
    for stream in listener.incoming() {
        thread::spawn(move || {
            handle_connection(stream.unwrap());
        });
    }
}

客户:

use std::net::TcpStream;
use std::io;
use std::io::Write;
use std::io::BufReader;
use std::io::BufRead;
use std::io::BufWriter;

fn main() {
    let stream = TcpStream::connect("127.0.0.1:8888")
        .unwrap();
    let stream_clone = stream.try_clone().unwrap();
    let mut reader = BufReader::new(stream);
    let mut writer = BufWriter::new(stream_clone);
    loop {
        let mut s = String::new();
        let mut response = String::new();
        io::stdin().read_line(&mut s).unwrap();
        writer.write(s.as_bytes()).unwrap();
        reader.read_line(&mut response).unwrap();
        println!("{}", response.trim());
    }
}

当我测试代码时,服务器根本不响应。我的猜测是write方法有问题。我是对的还是其他原因?

1 个答案:

答案 0 :(得分:5)

您需要刷新缓冲区:writer.flush()

固定服务器:

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

fn handle_connection(stream: TcpStream) {
    let stream_clone = stream.try_clone().unwrap();
    let mut reader = BufReader::new(stream);
    let mut writer = BufWriter::new(stream_clone);
    loop {
        let mut s = String::new();
        reader.read_line(&mut s).unwrap();
        writer.write(s.as_bytes()).unwrap();
        writer.flush().unwrap();
    }
}

fn main() {
    let listener = TcpListener::bind("127.0.0.1:8888")
        .unwrap();
    for stream in listener.incoming() {
        thread::spawn(move || {
            handle_connection(stream.unwrap());
        });
    }
}

客户:

use std::net::TcpStream;
use std::io;
use std::io::Write;
use std::io::BufReader;
use std::io::BufRead;
use std::io::BufWriter;

fn main() {
    let stream = TcpStream::connect("127.0.0.1:8888")
        .unwrap();
    let stream_clone = stream.try_clone().unwrap();
    let mut reader = BufReader::new(stream);
    let mut writer = BufWriter::new(stream_clone);
    loop {
        let mut s = String::new();
        let mut response = String::new();
        io::stdin().read_line(&mut s).unwrap();
        writer.write(s.as_bytes()).unwrap();
        writer.flush().unwrap();
        reader.read_line(&mut response).unwrap();
        println!("{}", response.trim());
    }
}