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

}

相关推荐
XUEYUAN52121 小时前
Cloudflare 防护机制深度剖析与跨境数据采集工程化实践
服务器·网络·网络协议·tcp/ip·http
青瓦梦滋1 小时前
IP/MAC帧/ARP协议
运维·服务器·网络·网络协议·tcp/ip
xx~t3 小时前
嵌入式——Linux软件编程2
linux·运维·服务器·c语言·学习方法
RisunJan3 小时前
Linux命令-vgchange(修改 LVM 卷组属性)
linux·运维·服务器
天启HTTP4 小时前
住宅IP和机房IP有什么区别?爬虫场景实测对比
爬虫·网络协议·tcp/ip
xiaojiaohuazi4 小时前
国产安陆EG4S20 FPGA实现千兆以太网TCP/IP:AD7606C 8通道1 MSPS采集、SDRAM缓存与Python上位机
tcp/ip·缓存·fpga开发
北风toto4 小时前
TCP/IP网络基础知识
网络·网络协议·tcp/ip
ZMacros4 小时前
Buildroot构建文件系统
linux·服务器
herinspace4 小时前
管家婆财贸ERP如何进行基本信息批量搬移
服务器·数据库·管家婆软件·财务软件