tokio: fix API doc examples (#1396)

This commit is contained in:
Carl Lerche
2019-08-06 14:03:49 -07:00
committed by GitHub
parent 2f43b0a023
commit 47e2ff48d9
18 changed files with 269 additions and 249 deletions
+29 -32
View File
@@ -33,10 +33,6 @@ the Rust programming language. It is:
[API Docs](https://docs.rs/tokio/0.1.22/tokio) |
[Chat](https://gitter.im/tokio-rs/tokio)
The API docs for the master branch are currently out of date as master is
undergoing significant churn as it is updated to use `std::future`. The docs
will be udpated once the branch stabilizes.
## Overview
Tokio is an event-driven, non-blocking I/O platform for writing
@@ -60,41 +56,42 @@ an asynchronous application.
A basic TCP echo server with Tokio:
```rust
use tokio::prelude::*;
use tokio::io::copy;
#![feature(async_await)]
use tokio::net::TcpListener;
use tokio::prelude::*;
fn main() {
// Bind the server's socket.
let addr = "127.0.0.1:12345".parse().unwrap();
let listener = TcpListener::bind(&addr)
.expect("unable to bind TCP listener");
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let addr = "127.0.0.1:8080".parse()?;
let mut listener = TcpListener::bind(&addr).unwrap();
// Pull out a stream of sockets for incoming connections
let server = listener.incoming()
.map_err(|e| eprintln!("accept failed = {:?}", e))
.for_each(|sock| {
// Split up the reading and writing parts of the
// socket.
let (reader, writer) = sock.split();
loop {
let (mut socket, _) = listener.accept().await?;
// A future that echos the data and returns how
// many bytes were copied...
let bytes_copied = copy(reader, writer);
tokio::spawn(async move {
let mut buf = [0; 1024];
// ... after which we'll print what happened.
let handle_conn = bytes_copied.map(|amt| {
println!("wrote {:?} bytes", amt)
}).map_err(|err| {
eprintln!("IO error {:?}", err)
});
// 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(n) if n == 0 => return,
Ok(n) => n,
Err(e) => {
println!("failed to read from socket; err = {:?}", e);
return;
}
};
// Spawn the future as a concurrent task.
tokio::spawn(handle_conn)
// Write the data back
if let Err(e) = socket.write_all(&buf[0..n]).await {
println!("failed to write to socket; err = {:?}", e);
return;
}
}
});
// Start the Tokio runtime
tokio::run(server);
}
}
```