以下是一个简单的Rust TCP服务器示例,它接受客户端连接,并将接收到的数据回显回客户端:
use std::io::{self, Read, Write};
use std::net::TcpListener;
fn main() -> io::Result<()> {
let listener = TcpListener::bind("127.0.0.1:8080")?;
println!("Listening on 127.0.0.1:8080");
for stream in listener.incoming() {
let stream = stream?;
handle_connection(stream)?;
}
Ok(())
}
fn handle_connection(mut stream: TcpStream) -> io::Result<()> {
let mut buffer = [0; 1024];
let bytes_read = stream.read(&mut buffer)?;
if bytes_read == 0 {
return Ok(());
}
println!("Received {} bytes: {:?}", bytes_read, &buffer[..bytes_read]);
// Echo the data back
stream.write_all(&buffer[..bytes_read])?;
stream.flush()?;
Ok(())
}