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

}

相关推荐
2301_7890156220 分钟前
Linux基础指令(一)
linux·运维·服务器·c语言·开发语言·c++·linux指令
晚风予卿云月1 小时前
【linux】进程优先级
linux·运维·服务器
wangl_921 小时前
Modbus RTU 与 Modbus TCP 深入指南-总览对比
网络·网络协议·tcp/ip·tcp·modbus·rtu
yyuuuzz1 小时前
aws注册过程中的常见问题梳理
运维·服务器·网络·云计算·github·aws
德迅云安全-小潘1 小时前
手游架设全攻略:服务器选型、配置与部署一站式指南
运维·服务器
wangl_921 小时前
Modbus RTU 与 Modbus TCP 深入指南-CRC校验完全解析
网络·网络协议·tcp/ip·tcp·modbus·rtu
辞山1 小时前
Coordinate SDK 技术解析
rust
Hical_W1 小时前
从 io_context 出发,掌握 C++20 协程式异步 I/O,学会 TCP 服务器、定时器和多线程模型,结合 Hical 框架实战解读
服务器·tcp/ip·开源·c++20
CDN3601 小时前
2026年服务器运维实战:从eBPF内核观测到Serverless边缘计算
运维·服务器·serverless
isyangli_blog1 小时前
7. 使用Mininet 创建回环网络拓扑
服务器·网络·php