Crate tokio

source · []
Expand description

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:

  • A multi threaded, work-stealing based task scheduler.
  • A reactor backed by the operating system’s event queue (epoll, kqueue, IOCP, etc…).
  • Asynchronous TCP and UDP sockets.
  • Asynchronous filesystem operations.
  • Timer API for scheduling work in the future.

Tokio is built using futures as the abstraction for managing the complexity of asynchronous programming.

Guide level documentation is found on the website.

Examples

A simple TCP echo server:

extern crate tokio;

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

fn main() {
    // Bind the server's socket.
    let addr = "127.0.0.1:12345".parse().unwrap();
    let listener = TcpListener::bind(&addr)
        .expect("unable to bind TCP listener");

    // Pull out a stream of sockets for incoming connections
    let server = listener.incoming()
        .map_err(|e| eprintln!("accept failed = {:?}", e))
        .for_each(|sock| {
            // Split up the reading and writing parts of the
            // socket.
            let (reader, writer) = sock.split();

            // A future that echos the data and returns how
            // many bytes were copied...
            let bytes_copied = copy(reader, writer);

            // ... after which we'll print what happened.
            let handle_conn = bytes_copied.map(|amt| {
                println!("wrote {:?} bytes", amt)
            }).map_err(|err| {
                eprintln!("IO error {:?}", err)
            });

            // Spawn the future as a concurrent task.
            tokio::spawn(handle_conn)
        });

    // Start the Tokio runtime
    tokio::run(server);
}

Re-exports

pub use executor::spawn;

Modules

A configurable source of time.

Utilities for encoding and decoding frames.

Task execution utilities.

Asynchronous filesystem manipulation operations.

Asynchronous I/O.

TCP/UDP/Unix bindings for tokio.

A “prelude” for users of the tokio crate.

Event loop that drives Tokio I/O resources.

A batteries included runtime for applications using Tokio.

Future-aware synchronization

Utilities for tracking time.

Utilities for working with Tokio.

Functions

Start the Tokio runtime using the supplied future to bootstrap execution.