3 KiB
Writing an Accept Loop
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:
#![feature(async_await)]
use std::net::ToSocketAddrs; // 1
use async_std::{
prelude::*, // 2
task, // 3
net::TcpListener, // 4
};
type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>; // 5
async_stdusesstdtypes where appropriate. We'll needToSocketAddrsto specify address to listen on.preludere-exports some traits required to work with futures and streams.- The
taskmodule roughly corresponds to thestd::threadmodule, but tasks are much lighter weight. A single thread can run many tasks. - For the socket type, we use
TcpListenerfromasync_std, which is just likestd::net::TcpListener, but is non-blocking and usesasyncAPI. - We will skip implementing comprehensive 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:
async fn server(addr: impl ToSocketAddrs) -> Result<()> { // 1
let listener = TcpListener::bind(addr).await?; // 2
let mut incoming = listener.incoming();
while let Some(stream) = incoming.next().await { // 3
// TODO
}
Ok(())
}
-
We mark the
serverfunction asasync, which allows us to use.awaitsyntax inside. -
TcpListener::bindcall returns a future, which we.awaitto extract theResult, and then?to get aTcpListener. Note how.awaitand?work nicely together. This is exactly howstd::net::TcpListenerworks, but with.awaitadded. Mirroring API ofstdis an explicit design goal ofasync_std. -
Here, we would like to iterate incoming sockets, just how one would do in
std:let listener: std::net::TcpListener = unimplemented!(); for stream in listener.incoming() { }Unfortunately this doesn't quite work with
asyncyet, because there's no support forasyncfor-loops in the language yet. For this reason we have to implement the loop manually, by usingwhile let Some(item) = iter.next().awaitpattern.
Finally, let's add main:
fn main() -> Result<()> {
let fut = server("127.0.0.1:8080");
task::block_on(fut)
}
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 handle it to the executor.
In this case, we use task::block_on to execute a future on the current thread and block until it's done.