summaryrefslogtreecommitdiff
path: root/examples/udp_async.rs
blob: 4c2ba2125773f008e611f8126f155fd23b984864 (plain)
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
//! Echo example.
//! Use `nc -u 127.0.0.1 30000` to connect.

use mini_rust_runtime::executor::Executor;
use mini_rust_runtime::udp2::UdpSocket;
use tokio::io::{AsyncReadExt, AsyncWriteExt};

fn main() {
    let ex = Executor::new(); // 执行器实例
    ex.block_on(server); // 协程最开始的地方
}

async fn server() {
    let socket: UdpSocket = UdpSocket::bind("127.0.0.1:30000").unwrap();
    let mut buf: [u8; 4096] = [0; 4096];
    loop {
        match socket.recv_from_async(&mut buf).await {
            Ok((n, addr)) => {
                println!("recv_from {} {} bytes", addr, n);
                if n == 0 || socket.send_to_async(&buf[..n], &addr).await.is_err() {
                    // 回写
                    return;
                }
            }
            Err(_) => {
                return;
            }
        }
    }
}