rust实现TCP服务器

以下是一个简单的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(())

}

相关推荐
sulikey7 分钟前
Linux基础指令与权限管理深度解析:从入门到精通
linux·运维·服务器·ubuntu·centos·linux命令·linux权限
xu_yule37 分钟前
网络和Linux网络-3(套接字编程)TCP网络通信代码
linux·网络·tcp/ip
周杰伦fans1 小时前
C# - Task 是什么?想象一下你在餐厅点餐
服务器·开发语言·c#
芳草萋萋鹦鹉洲哦1 小时前
【tauri+rust】App会加载白屏,有时显示在左上角显示一小块,如何优化
开发语言·后端·rust
zengyuhan5032 小时前
Windows BLE 开发指南(Rust windows-rs)
前端·rust
醉方休2 小时前
Webpack loader 的执行机制
前端·webpack·rust
HalvmånEver2 小时前
Linux:进程的切换与调度(进程四)
linux·运维·服务器
泡沫·3 小时前
8.项目实战:Ecshop
服务器
1***s6323 小时前
Rust在WebAssembly中的应用实践
开发语言·rust·wasm
脏脏a4 小时前
【Linux】Linux进程状态深度解析
linux·运维·服务器