[−][src]Crate smol
A small and fast executor.
This crate runs a global executor thread pool and only has one type, Task
. Despite the
trivially simple codebase, this executor and its related crates offer performance and features
comparable to more complex frameworks like tokio.
Related async crates:
- For async I/O and timers, use
async-io
. - For higher-level networking primitives, use
async-net
. - For executors, use
multitask
. - To call blocking code from async code or the other way around, use
blocking
. - For async traits and combinators, use
futures-lite
.
TCP server
A simple TCP server that prints messages received from clients:
use async_io::Async; use blocking::{block_on, Unblock}; use smol::Task; use std::net::TcpListener; fn main() -> std::io::Result<()> { block_on(async { // Start listening on port 9000. let listener = Async::<TcpListener>::bind(([127, 0, 0, 1], 9000))?; loop { // Accept a new client. let (stream, _) = listener.accept().await?; // Spawn a task handling this client. let task = Task::spawn(async move { // Create an async stdio handle. let mut stdout = Unblock::new(std::io::stdout()); // Copy data received from the client into stdout. futures::io::copy(&stream, &mut stdout).await }); // Keep running the task in the background. task.detach(); } }) }
To interact with the server, run nc 127.0.0.1 9000
and type a few lines of text.
Examples
Look inside the examples directory for more: a web crawler, a Ctrl-C handler, a TCP client/server, a TCP chat client/server, a TLS client/server, an HTTP+TLS client/server, an async-h1 client/server, a hyper client/server, and a WebSocket+TLS client/server.
It's also possible to plug non-async libraries into the runtime: see inotify, timerfd, signal-hook, and uds_windows.
Finally, there's an example showing how to use smol with async-std, tokio, surf, and reqwest.
Structs
Task | A spawned future. |