[][src]Crate tokio

A runtime for writing reliable, asynchronous, and slim applications.

Tokio is an event-driven, non-blocking I/O platform for writing asynchronous applications with the Rust programming language. At a high level, it provides a few major components:

Guide level documentation is found on the website.

Examples

A simple TCP echo server:

use tokio::net::TcpListener;
use tokio::prelude::*;

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

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

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

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

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

Re-exports

pub use tokio_macros::main;
pub use tokio_macros::test;

Modules

clock

A configurable source of time.

codec

Utilities for encoding and decoding frames.

executor

Task execution utilities.

fs

Asynchronous filesystem manipulation operations.

future

Asynchronous values.

io

Asynchronous I/O.

net

TCP/UDP/Unix bindings for tokio.

prelude

A "prelude" for users of the tokio crate.

runtime

A batteries included runtime for applications using Tokio.

stream

A sequence of asynchronous values.

sync

Future-aware synchronization

timer

Utilities for tracking time.

Functions

spawn

Spawns a future on the default executor.