通过 Rust 学习网络编程

TCP Server/Client

TCP C/S

Server:

 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
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(Duration::from_secs(1));
    }
    Ok(())
}

fn main() -> io::Result<()> {
    let listener = TcpListener::bind("127.0.0.1:8080")?;
    println!("TCP Server is running...");

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

Client:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
fn main() -> io::Result<()> {
    let mut stream = TcpStream::connect("127.0.0.1:8080")?;
    println!("TCP Client is running...");

    for _ in 0..10 {
        let mut input = String::new();
        io::stdin().read_line(&mut input).expect("Failed to read");
        stream.write(input.as_bytes()).expect("Failed to write");

        let mut reader = BufReader::new(&stream);
        let mut buffer = vec![];
        reader
            .read_until(b'\n', &mut buffer)
            .expect("Failed to read");
        println!(
            "Read from server: {}",
            std::str::from_utf8(&buffer).expect("Failed to accept")
        );
    }
    Ok(())
}

UDP Server/Client

UDP C/S

Server:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
fn main() -> io::Result<()> {
    let socket = UdpSocket::bind("127.0.0.1:8080")?;
    println!("UDP socket is running...");

    loop {
        let mut buf = [0; 1500];
        let (amt, src) = socket.recv_from(&mut buf)?;

        let buf = &mut buf[..amt];
        buf.reverse();
        socket.send_to(buf, src)?;
    }
}

Client:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
fn main() -> io::Result<()> {
    let socket = UdpSocket::bind("127.0.0.1:8081")?;
    println!("UDP socket is running...");
    socket.connect("127.0.0.1:8080")?;

    loop {
        let mut input = String::new();
        io::stdin().read_line(&mut input)?;
        socket.send(input.as_bytes())?;

        let mut buf = [0; 1500];
        let bytes_read = socket.recv(&mut buf)?;
        println!(
            "Receive: {}",
            std::str::from_utf8(&buf[..bytes_read]).expect("Invaild message")
        );
    }
}

IP/Socket Address

Homework

Documentations

这里列举视频中一些概念相关的 documentation

学习的一手资料是官方文档,请务必自主学会阅读规格书之类的资料

Crate std

Crate ipnet

0%