summaryrefslogtreecommitdiff
path: root/examples/echo.rs
blob: 644627ab30020f5534f298f06a9fd43f7570937d (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
31
32
33
34
35
36
37
//! Echo example.
//! Use `nc 127.0.0.1 30000` to connect.

use futures::StreamExt;
use mini_rust_runtime::executor::Executor;
use mini_rust_runtime::tcp::TcpListener;
use tokio::io::{AsyncReadExt, AsyncWriteExt};

fn main() {
    let ex = Executor::new();
    ex.block_on(serve);
}

async fn serve() {
    let mut listener = TcpListener::bind("127.0.0.1:30000").unwrap();
    while let Some(ret) = listener.next().await {
        if let Ok((mut stream, addr)) = ret {
            println!("accept a new connection from {} successfully", addr);
            let f = async move {
                let mut buf = [0; 4096];
                loop {
                    match stream.read(&mut buf).await {
                        Ok(n) => {
                            if n == 0 || stream.write_all(&buf[..n]).await.is_err() {
                                return;
                            }
                        }
                        Err(_) => {
                            return;
                        }
                    }
                }
            };
            Executor::spawn(f);
        }
    }
}