Tokio入门

学习tokio的目的是啥

其实俺想把rustdesk的udp用tcp实现了,这样就能很容易的经过公司的http proxy了

第一个例子tcp echo server

[dependencies]
tokio = { version = "1.11.0", features = ["full"] }
use tokio::net::TcpListener;
use tokio::io::{AsyncReadExt, AsyncWriteExt};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let listener = TcpListener::bind("127.0.0.1:8080").await?;

    loop {
        let (mut socket, addr) = listener.accept().await?;

        tokio::spawn(async move {
            let mut buf = [0; 1024];

            async fn handle_msg (socket:& mut tokio::net::TcpStream, buf: &mut [u8]) -> Result<(), std::io::Error>{
                let n = socket.read(buf).await?;
                if n==0 {return Ok(());}

                // Write the data back
                socket.write_all(&buf[0..n]).await
            }
            // In a loop, read data from the socket and write the data back.
            loop {
                handle_msg(&mut socket, &mut buf);
            }
        });
    }
}

flow chart

digraph x{
    start -> TcpListener [label="bind"];
    TcpListener -> TcpStream  [ label="accept" ];
    TcpStream -> data [label="read"];
}

client flow chart

digraph x{
start -> TcpStream [label="TcpStream ::connect"] 
TcpStream -> Connection [label="Connection::new"]
Connection  -> remote_server [label="write_frame"]
remote_server -> Connection  [label="write_frame"]
}

channels

let (tx, mut rx) = mpsc::channel(32);
    let tx2 = tx.clone();


tx.send("sending from first handle").await;

rx.recv().await?;

I/O

use tokio::fs::File;


let mut f = File::open("foo.txt").await?;
let n = f.read(&mut buffer[..]).await?;
f.read_to_end(&mut buffer).await?;
let n = file.write(b"some bytes").await?;
buffer.write_all(b"some bytes").await?;


io::copy(&mut reader, &mut file).await?;



Powered by Jekyll and Theme by solid

本站总访问量