tokio README

The project's README from github.com/tokio-rs/tokio. As one markdown file: README.md.

Tokio

A runtime for writing reliable, asynchronous, and slim applications with the Rust programming language. It is:

Crates.io MIT licensed Build Status Discord chat

Website | Guides | API Docs | Chat

Overview

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:

These components provide the runtime components necessary for building an asynchronous application.

Example

A basic TCP echo server with Tokio.

Make sure you enable the full features of the tokio crate on Cargo.toml:

[dependencies]
tokio = { version = "1.53.1", features = ["full"] }

Then, on your main.rs:

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, _) = 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(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;
                }
            }
        });
    }
}

More examples can be found here. For a larger "real world" example, see the mini-redis repository.

To see a list of the available feature flags that can be enabled, check our docs.

Getting Help

First, see if the answer to your question can be found in the Guides or the API documentation. If the answer is not there, there is an active community in the Tokio Discord server. We would be happy to try to answer your question. You can also ask your question on the discussions page.

Contributing

:balloon: Thanks for your help improving the project! We are so happy to have you! We have a contributing guide to help you get involved in the Tokio project.

In addition to the crates in this repository, the Tokio project also maintains several other libraries, including:

Changelog

The Tokio repository contains multiple crates. Each crate has its own changelog.

Supported Rust Versions

Tokio will keep a rolling MSRV (minimum supported rust version) policy of at least 6 months. When increasing the MSRV, the new Rust version must have been released at least six months ago. The current MSRV is 1.71.

Note that the MSRV is not increased automatically, and only as part of a minor release. The MSRV history for past minor releases can be found below:

Note that although we try to avoid the situation where a dependency transitively increases the MSRV of Tokio, we do not guarantee that this does not happen. However, every minor release will have some set of versions of dependencies that works with the MSRV of that minor release.

Release schedule

Tokio doesn't follow a fixed release schedule, but we typically make one minor release each month. We make patch releases for bugfixes as necessary.

Bug patching policy

For the purposes of making patch releases with bugfixes, we have designated certain minor releases as LTS (long term support) releases. Whenever a bug warrants a patch release with a fix for the bug, it will be backported and released as a new patch release for each LTS minor version. Our current LTS releases are:

Each LTS release will continue to receive backported fixes for at least a year. If you wish to use a fixed minor release in your project, we recommend that you use an LTS release.

To use a fixed minor version, you can specify the version with a tilde. For example, to specify that you wish to use the newest 1.47.x patch release, you can use the following dependency specification:

tokio = { version = "~1.47", features = [...] }

Previous LTS releases

License

This project is licensed under the MIT license.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in Tokio by you shall be licensed as MIT, without any additional terms or conditions.

tokio (tokio-rs/tokio)

Searching Database…

33.4K ·GitHub
Что это такое?Tokio — это среда выполнения (runtime) для написания надёжных асинхронных приложений на Rust: она даёт планировщик, неблокирующий ввод-вывод, работу с сетью и таймеры, которые нужны асинхронным программам на Rust.
То есть это библиотека, которую я подключаю к своему Rust-проекту, или отдельная программа?Это библиотека, а не приложение: ваш проект зависит от крейта tokio (в репозитории также есть tokio-util, tokio-stream, tokio-macros и tokio-test), а ваш код выполняется на планировщике Tokio.
Как добавить её в проект?Добавьте крейт tokio в свой Cargo.toml — в примере из README включён набор фич 'full' — затем пишите асинхронный код в main.rs; пример TCP echo-сервера показывает базовую структуру.
Мне нужна какая-то определённая версия Rust?Да, достаточно свежий набор инструментов: минимальная поддерживаемая версия Rust (MSRV) сейчас — 1.71, и она повышается только в минорных релизах, причём не раньше чем через шесть месяцев после выхода соответствующей версии Rust.
Она одинаково работает на Linux, macOS и Windows?Да — в README перечислены штатные очереди событий ОС, на которых она строится: epoll (Linux), kqueue (macOS/BSD) и IOCP (Windows), так что все три основные настольные и серверные платформы поддерживаются.
Что Tokio даёт мне под капотом?Три основных компонента: многопоточный планировщик задач с перехватом работы (work-stealing); реактор, работающий на очереди событий операционной системы; и асинхронные TCP- и UDP-сокеты — вместе это те части runtime, которые нужны асинхронному приложению.
Где посмотреть пример побольше, чем echo-сервер, — что-то из реальной жизни?В репозитории есть и другие примеры, а команда рекомендует mini-redis — более крупный «реальный» проект, построенный на Tokio.
Какие ещё библиотеки поддерживает проект Tokio?Сопутствующие крейты: axum и warp (веб-фреймворки), hyper (HTTP/1.1 и HTTP/2), tonic (gRPC поверх HTTP/2), tower (компоненты для клиента и сервера), tracing (диагностика с поддержкой асинхронности), mio (низкоуровневый ввод-вывод ОС), bytes (буферы) и loom (тестирование многопоточности).
What are similar projects?libuv, compio, conc, muduo, libevent, disruptor, sidekiq, taskflow
Creator
tokio-rs
Size
17.6 MB
Stars
33.4K
Age
10y
Commits · 90 Days