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

}

相关推荐
古城小栈6 小时前
Rust 迭代器产出的引用层数——分水岭
开发语言·rust
cuijiecheng20187 小时前
Linux下Beyond Compare过期
linux·运维·服务器
期待のcode7 小时前
前后端分离项目 Springboot+vue 在云服务器上的部署
服务器·vue.js·spring boot
AI 智能服务8 小时前
第6课__本地工具调用(文件操作)
服务器·人工智能·windows·php
peterfei10 小时前
IfAI v0.2.8 技术深度解析:从"工具"到"平台"的架构演进
rust·ai编程
松涛和鸣10 小时前
49、智能电源箱项目技术栈解析
服务器·c语言·开发语言·http·html·php
凉、介10 小时前
SylixOS 中的 Unix Socket
服务器·c语言·笔记·学习·嵌入式·sylixos
RisunJan11 小时前
Linux命令-ipcs命令(报告进程间通信(IPC)设施状态的实用工具)
linux·运维·服务器
HABuo12 小时前
【Linux进程(四)】进程切换&环境变量深入剖析
linux·运维·服务器·c语言·c++·ubuntu·centos