diff options
author | Carl Lerche <me@carllerche.com> | 2019-08-06 14:03:49 -0700 |
---|---|---|
committer | GitHub <noreply@github.com> | 2019-08-06 14:03:49 -0700 |
commit | 47e2ff48d9f1daac7dba9f136b24eed64c87cf40 (patch) | |
tree | 2c3ec343ec2ac5559fcd8ade8a914b7d5f61606d /README.md | |
parent | 2f43b0a023f155a3efed4b048f5e0822072840f8 (diff) |
tokio: fix API doc examples (#1396)
Diffstat (limited to 'README.md')
-rw-r--r-- | README.md | 69 |
1 files changed, 33 insertions, 36 deletions
@@ -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"); - - // 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(); - - // A future that echos the data and returns how - // many bytes were copied... - let bytes_copied = copy(reader, writer); - - // ... 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) - }); - - // Spawn the future as a concurrent task. - tokio::spawn(handle_conn) +#[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(); + + loop { + let (mut socket, _) = listener.accept().await?; + + tokio::spawn(async move { + let mut buf = [0; 1024]; + + // 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; + } + }; + + // 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); + } } ``` |