以下代码基于std :: net :: TcpListener上的文档提供的示例。该服务器应用程序将侦听传入的请求并发送回所有传入的数据,从而充当“回显”服务器。客户端应用程序将发送一条小消息,并期望包含相同内容的答复。
服务器:
use std::thread; use std::net::{TcpListener, TcpStream, Shutdown}; use std::io::{Read, Write}; fn handle_client(mut stream: TcpStream) { let mut data = [0 as u8; 50]; // 使用50字节缓冲区 while match stream.read(&mut data) { Ok(size) => { // 呼应一切! stream.write(&data[0..size]).unwrap(); true }, Err(_) => { println!("An error occurred, terminating connection with {}", stream.peer_addr().unwrap()); stream.shutdown(Shutdown::Both).unwrap(); false } } {} } fn main() { let listener = TcpListener::bind("0.0.0.0:3333").unwrap(); // 接受连接并处理它们,为每个连接产生一个新线程 println!("Server listening on port 3333"); for stream in listener.incoming() { match stream { Ok(stream) => { println!("New connection: {}", stream.peer_addr().unwrap()); thread::spawn(move|| { // 连接成功 handle_client(stream) }); } Err(e) => { println!("Error: {}", e); /* connection failed */ } } } // 关闭套接字服务器 drop(listener); }
客户:
use std::net::{TcpStream}; use std::io::{Read, Write}; use std::str::from_utf8; fn main() { match TcpStream::connect("localhost:3333") { Ok(mut stream) => { println!("Successfully connected to server in port 3333"); let msg = b"Hello!"; stream.write(msg).unwrap(); println!("Sent Hello, awaiting reply..."); let mut data = [0 as u8; 6]; // 使用6字节缓冲区 match stream.read_exact(&mut data) { Ok(_) => { if &data == msg { println!("可以回复!"); } else { let text = from_utf8(&data).unwrap(); println!("Unexpected reply: {}", text); } }, Err(e) => { println!("Failed to receive data: {}", e); } } }, Err(e) => { println!("Failed to connect: {}", e); } } println!("Terminated."); }