您需要刷新缓冲区:
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());
}
}