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(())

}

相关推荐
程序猿(雷霆之王)1 天前
Linux——线程安全
linux·运维·服务器
wanhengidc1 天前
云手机畅玩 梦幻西游
运维·服务器·arm开发·智能手机·自动化
熊猫_豆豆1 天前
回调函数的作用与举例(Python版)
服务器·python·编程语法
VincentHe1 天前
当 ServerCat 遇上 Shell 环境变量:一次服务器监控性能优化记录与探索
服务器·shell·监控
深耕AI1 天前
如何在云服务器上找回并配置宝塔面板:完整指南
运维·服务器
电化学仪器白超1 天前
④使用 PPTSYNC.exe 与华为手机拍照制作 GIF 动画
服务器·华为·智能手机
jerryinwuhan1 天前
Linux常用命令练习题
linux·运维·服务器
tang777891 天前
对抗高级反爬:基于动态代理 IP 的浏览器指纹模拟与轮换策略
网络·网络协议·tcp/ip
林太白1 天前
Rust14-字典数据
后端·rust
阿银1 天前
如何为 macOS 创建 Rust 通用二进制文件 (x86_64 & aarch64)
rust·electron