2个稳定版本

2.0.0 2024年5月1日
1.0.0 2024年4月29日

#355异步

0BSD 许可证

6KB
51

基于:基于异步单线程执行调度器

tokio_based 的目的是允许你轻松启动一个单线程的 tokio 运行时。当 join 处理程序被丢弃时,这将关闭并且所有任务将被丢弃。

struct ExampleServer {
    join_handle: tokio_based::JoinHandle,
}

impl ExampleServer {
    fn new() -> ExampleServer {
        let join_handle = tokio_based::spawn(|run| async move {
            let listener = TcpListener::bind("127.0.0.1:8080").await.unwrap();

            while run.load(Ordering::SeqCst) {
                let (mut socket, _) = listener.accept().await.unwrap();

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

                        // In a loop, read data from the socket and write the data back.
                        while run.load(Ordering::SeqCst) {
                            let n = match socket.read(&mut buf).await {
                                // socket closed
                                Ok(0) => return,
                                Ok(n) => n,
                                Err(e) => {
                                    eprintln!("failed to read from socket; err = {:?}", e);
                                    return;
                                }
                            };

                            // Write the data back
                            if let Err(e) = socket.write_all(&buf[0..n]).await {
                                eprintln!("failed to write to socket; err = {:?}", e);
                                return;
                            }
                        }
                    }
                });
            }
        });

        ExampleServer { join_handle }
    }
}

依赖项

~2–3MB
~47K SLoC