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

}

相关推荐
该用户已不存在15 小时前
Mojo vs Python vs Rust: 2025年搞AI,该学哪个?
后端·python·rust
大卫小东(Sheldon)18 小时前
写了一个BBP算法的实现库,欢迎讨论
数学·rust
christine-rr1 天前
linux常用命令(4)——压缩命令
linux·服务器·redis
東雪蓮☆1 天前
深入理解 LVS-DR 模式与 Keepalived 高可用集群
linux·运维·服务器·lvs
echoarts1 天前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
树码小子1 天前
Java网络编程:(socket API编程:TCP协议的 socket API -- 回显程序的服务器端程序的编写)
java·网络·tcp/ip
乌萨奇也要立志学C++1 天前
【Linux】进程概念(二):进程查看与 fork 初探
linux·运维·服务器
绿箭柠檬茶1 天前
Ubuntu 服务器配置转发网络访问
服务器·网络·ubuntu
獭.獭.1 天前
Linux -- 信号【上】
linux·运维·服务器
路由侠内网穿透1 天前
本地部署 GPS 跟踪系统 Traccar 并实现外部访问
运维·服务器·网络·windows·tcp/ip