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

}

相关推荐
Rverdoser7 小时前
网站开发用什么语言好
服务器
四时久成8 小时前
服务器认证系统
运维·服务器
徐子元竟然被占了!!8 小时前
Windows Server 2019 DateCenter搭建 FTP 服务器
运维·服务器·windows
wayuncn10 小时前
影响服务器托管费用的因素
运维·服务器·数据中心·服务器托管·物理服务器租用·服务器机柜·idc机房托管
喜欢你,还有大家10 小时前
Linux笔记10——shell编程基础-4
linux·运维·服务器·笔记
玩转以太网10 小时前
基于 W55MH32Q-EVB 实现 FatFs 文件系统+FTP 服务器
服务器·单片机·物联网
不懂机器人10 小时前
linux编程----网络通信(TCP)
linux·服务器·tcp/ip
✎﹏赤子·墨筱晗♪10 小时前
服务器初始化
运维·服务器
会飞的鱼_12311 小时前
CentOS 7服务器初始化全攻略:从基础配置到安全加固
服务器·安全·centos
tanyongxi6611 小时前
简易shell
linux·运维·服务器