mirror of
https://github.com/tokio-rs/tokio.git
synced 2026-08-21 00:00:10 +02:00
This patch adds experimental async/await support to Tokio. It does this by adding feature flags to existing libs only where necessary in order to add nightly specific code (mostly `Unpin` implementations). It then provides a new crate: `tokio-async-await` which is a shim layer on top of `tokio`. The `tokio-async-await` crate is expected to look exactly like `tokio` does, but with async / await support. This strategy reduces the amount of cfg guarding in the main libraries. This patch also adds `tokio-channel`, which is copied from futures-rs 0.1 and adds the necessary `Unpin` implementations. In general, futures 0.1 is mostly unmaintained, so it will make sense for Tokio to take over maintainership of key components regardless of async / await support.
46 lines
1.1 KiB
Rust
46 lines
1.1 KiB
Rust
#![feature(await_macro, async_await)]
|
|
|
|
#[macro_use]
|
|
extern crate tokio;
|
|
|
|
use tokio::net::{TcpListener, TcpStream};
|
|
use tokio::prelude::*;
|
|
|
|
use std::net::SocketAddr;
|
|
|
|
fn handle(mut stream: TcpStream) {
|
|
tokio::spawn_async(async move {
|
|
let mut buf = [0; 1024];
|
|
|
|
loop {
|
|
match await!(stream.read_async(&mut buf)).unwrap() {
|
|
0 => break, // Socket closed
|
|
n => {
|
|
// Send the data back
|
|
await!(stream.write_all_async(&buf[0..n])).unwrap();
|
|
}
|
|
}
|
|
}
|
|
});
|
|
}
|
|
|
|
fn main() {
|
|
use std::env;
|
|
|
|
let addr = env::args().nth(1).unwrap_or("127.0.0.1:8080".to_string());
|
|
let addr = addr.parse::<SocketAddr>().unwrap();
|
|
|
|
// Bind the TCP listener
|
|
let listener = TcpListener::bind(&addr).unwrap();
|
|
println!("Listening on: {}", addr);
|
|
|
|
tokio::run_async(async {
|
|
let mut incoming = listener.incoming();
|
|
|
|
while let Some(stream) = await!(incoming.next()) {
|
|
let stream = stream.unwrap();
|
|
handle(stream);
|
|
}
|
|
});
|
|
}
|