整体设计思路
- 监听连接:使用
TcpListener
绑定到指定的地址和端口,监听客户端连接。
- 并发处理:每当有新的客户端连接到来时,将该连接的处理任务交给一个新的执行单元(线程或异步任务),这样服务器就可以同时处理多个客户端的请求。
利用线程实现并发处理
- 核心代码框架
use std::net::TcpListener;
use std::thread;
fn handle_connection(stream: std::net::TcpStream) {
// 处理客户端连接的逻辑
// 例如读取和写入数据
}
fn main() {
let listener = TcpListener::bind("127.0.0.1:8080").expect("Failed to bind");
for stream in listener.incoming() {
let stream = stream.expect("Failed to accept");
thread::spawn(move || {
handle_connection(stream);
});
}
}
利用异步实现并发处理
- 引入依赖:在
Cargo.toml
中添加 tokio
等异步相关依赖。
[dependencies]
tokio = { version = "1", features = ["full"] }
- 核心代码框架
use tokio::net::TcpListener;
async fn handle_connection(stream: tokio::net::TcpStream) {
// 异步处理客户端连接的逻辑
// 例如异步读取和写入数据
}
#[tokio::main]
async fn main() {
let listener = TcpListener::bind("127.0.0.1:8080").await.expect("Failed to bind");
loop {
let (stream, _) = listener.accept().await.expect("Failed to accept");
tokio::spawn(handle_connection(stream));
}
}