Let's implement the scaffold of the server: a loop that binds a TCP socket to an address and starts accepting connections.
First of all, let's add required import boilerplate:
# extern crate tokio;
use std::future::Future; // 1
use tokio::{
io::{AsyncBufReadExt, AsyncWriteExt, BufReader}, // 1
net::{tcp::OwnedWriteHalf, TcpListener, TcpStream, ToSocketAddrs}, // 3
sync::{mpsc, oneshot},
task, // 2
};
type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>; // 4
- Import some traits required to work with futures and streams.
- The
task
module roughly corresponds to thestd::thread
module, but tasks are much lighter weight. A single thread can run many tasks. - For the socket type, we use
TcpListener
fromtokio
, which is similar to the syncstd::net::TcpListener
, but is non-blocking and usesasync
API. - We will skip implementing detailled error handling in this example.
To propagate the errors, we will use a boxed error trait object.
Do you know that there's
From<&'_ str> for Box<dyn Error>
implementation in stdlib, which allows you to use strings with?
operator?
Now we can write the server's accept loop:
# extern crate tokio;
# use tokio::net::{TcpListener, ToSocketAddrs};
# type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>;
#
async fn accept_loop(addr: impl ToSocketAddrs) -> Result<()> { // 1
let listener = TcpListener::bind(addr).await?; // 2
loop { // 3
let (stream, _) = listener.accept().await?;
// TODO
}
Ok(())
}
- We mark the
accept_loop
function asasync
, which allows us to use.await
syntax inside. TcpListener::bind
call returns a future, which we.await
to extract theResult
, and then?
to get aTcpListener
. Note how.await
and?
work nicely together. This is exactly howstd::net::TcpListener
works, but with.await
added.- We generally use
loop
andbreak
for looping in Futures, that makes things easier down the line.
Finally, let's add main:
# extern crate tokio;
# use tokio::net::{ToSocketAddrs};
# type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>;
# async fn accept_loop(addr: impl ToSocketAddrs) -> Result<()> {
# Ok(())
# }
#
#[tokio::main]
pub(crate) async fn main() -> Result<()> {
accept_loop("127.0.0.1:8080").await
}
The crucial thing to realise that is in Rust, unlike other languages, calling an async function does not run any code.
Async functions only construct futures, which are inert state machines.
To start stepping through the future state-machine in an async function, you should use .await
.
In a non-async function, a way to execute a future is to hand it to the executor.