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

}

相关推荐
风行無痕3 小时前
Ubuntu Linux系统配置账号无密码sudo
linux·服务器·ubuntu
明月看潮生3 小时前
青少年编程与数学 02-019 Rust 编程基础 05课题、复合数据类型
开发语言·青少年编程·rust·编程与数学
SZ1701102314 小时前
中继器的作用
服务器·网络·智能路由器
chenxy024 小时前
如何快速分享服务器上的文件
运维·服务器
重启就好5 小时前
【Ansible】模块详解
linux·服务器·ansible
SuperW6 小时前
Linxu实验五——NFS服务器
运维·服务器
promise5246 小时前
JVM之jcmd命令详解
java·linux·运维·服务器·jvm·bash·jcmd
果子⌂6 小时前
Linux系统入门第十二章 --Shell编程之正则表达式
linux·运维·服务器
海尔辛7 小时前
学习黑客5 分钟读懂Linux Filesystem Interaction Continued
linux·服务器·学习
学习2年半7 小时前
服务器mysql连接我碰到的错误
运维·服务器·mysql