Tokio is an asynchronous runtime for the Rust programming language. It provides the building blocks needed for writing networking applications. It gives the flexibility to target a wide range of systems, from large servers with dozens of cores to small embedded devices.
At a high level, Tokio provides a few major components:
Here you can find the full code for a few little examples: Github!
Clone the repo and try it your self to see how it works in practice.
Tokio has a very good documentation. You can find it here! Go check it out.
use tokio::net::TcpStream;
async fn my_async_fn() {
println!("hello from async");
let _socket = TcpStream::connect("127.0.0.1:3000").await.unwrap();
println!("async TCP operation complete");
}
We call the function and it returns some value. We call .await
on that value.
#[tokio::main]
async fn main() {
let what_is_this =my_async_fn();
// Nothing has been printed yet.
what_is_this.await;
// Text has been printed and socket has been// established and closed.
}
The value returned by my_async_fn()
is a future. A future is a value that implements the std::future::Future
trait provided by the standard library. They are values that contain the in-progress asynchronous computation.
The std::future::Future
trait definition is:
use std::pin::Pin;
use std::task::{Context, Poll};
pub trait Future {
type Output;
fn poll(self: Pin<&mut Self>, cx: &mut Context)
-> Poll<Self::Output>;
}