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

}

相关推荐
Dola_Pan22 分钟前
Linux文件IO(二)-文件操作使用详解
java·linux·服务器
城南云小白2 小时前
Linux网络服务只iptables防火墙工具
linux·服务器·网络
从心归零2 小时前
sshj使用代理连接服务器
java·服务器·sshj
咩咩大主教2 小时前
C++基于select和epoll的TCP服务器
linux·服务器·c语言·开发语言·c++·tcp/ip·io多路复用
羌俊恩2 小时前
视频服务器:GB28181网络视频协议
服务器·网络·音视频
运维小白。。2 小时前
Nginx 反向代理
运维·服务器·nginx·http
科技互联人生2 小时前
中国数据中心服务器CPU行业发展概述
服务器·硬件架构
LvManBa4 小时前
Vue学习记录之六(组件实战及BEM框架了解)
vue.js·学习·rust
KookeeyLena54 小时前
云手机可以挂在服务器使用吗?
运维·服务器·智能手机
老汉忒cpp4 小时前
手动部署并测试内网穿透(ssh 和 nginx)
运维·服务器