Rust网络编程

Rust中TCP协议

TCP协议是网络编程中的一个重要概念,深入了解TCP协议,对网络开发有重要的作用。
TCP连接包括有三次握手和四次挥手,在Rust标准库的net模块中,实现了TCP协议。
NET模块

Rust中TCP协议的server端实现

Rust中TCP协议的server端主要由接收TCPListenerTCPStream 构成,其中使用
thread::spawn创建线程来处理到来的stream,使用handle_client方法实现。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
use std::net::{TcpListener, TcpStream};
use std::thread;
use std::time;
use std::io::{self, Read, Write};
fn handle_client(mut stream: TcpStream) -> io::Result<()> {
let mut buf = [0; 512];
for _ in 0..1000 {
let bytes_read = stream.read(&mut buf)?;
if bytes_read == 0 {
return Ok(())
}

stream.write(&buf[..bytes_read])?;
thread::sleep(time::Duration::from_secs(1));
}
Ok(())
}
fn main() -> io::Result<()> {
let listener = TcpListener::bind("127.0.0.1:8595")?;
let mut thread_vec: Vec<thread::JoinHandle<()>> = Vec::new();

for stream in listener.incoming() {
let stream = stream.expect("failed");
let handle = thread::spawn(move || {
handle_client(stream).
unwrap_or_else(
|error| eprintln!("{:?}", error)
)
});
thread_vec.push(handle);
}

for handle in thread_vec {
handle.join().unwrap();
}
Ok(())
}