Files
h2/examples/client.rs
Eliza Weisman 00ca534c4a Update examples to use new Tokio (#316)
The old `tokio-core` crate is deprecated in favour of the `tokio` crate,
which also provides the new multithreaded Tokio runtime. Although `h2`
is generic over the runtime, the examples do depend on `tokio`. 

This branch update the example code to use the new `tokio` library
rather than `tokio-core`. It also updates the examples in `RustDoc`.

For the most part, this was pretty trivial --- simply replacing
`handle.spawn(...)` with `tokio::spawn(...)` and `core.run(...)` with
`tokio::run(...)`. There were a couple of cases where error and item
types from spawned futures had to be mapped to `(), ()`. Alternatively,
this could have been avoided by using the single-threaded runtime and
calling `block_on` instead to await the value of those futures, but I
thought it was better to reduce the amount of tokio-specific code in the
examples.

Signed-off-by: Eliza Weisman <eliza@buoyant.io>
2018-09-25 14:33:49 -07:00

94 lines
2.3 KiB
Rust

extern crate env_logger;
extern crate futures;
extern crate h2;
extern crate http;
extern crate tokio;
use h2::client;
use h2::RecvStream;
use futures::*;
use http::*;
use tokio::net::TcpStream;
struct Process {
body: RecvStream,
trailers: bool,
}
impl Future for Process {
type Item = ();
type Error = h2::Error;
fn poll(&mut self) -> Poll<(), h2::Error> {
loop {
if self.trailers {
let trailers = try_ready!(self.body.poll_trailers());
println!("GOT TRAILERS: {:?}", trailers);
return Ok(().into());
} else {
match try_ready!(self.body.poll()) {
Some(chunk) => {
println!("GOT CHUNK = {:?}", chunk);
},
None => {
self.trailers = true;
},
}
}
}
}
}
pub fn main() {
let _ = env_logger::try_init();
let tcp = TcpStream::connect(&"127.0.0.1:5928".parse().unwrap());
let tcp = tcp.then(|res| {
let tcp = res.unwrap();
client::handshake(tcp)
}).then(|res| {
let (mut client, h2) = res.unwrap();
println!("sending request");
let request = Request::builder()
.uri("https://http2.akamai.com/")
.body(())
.unwrap();
let mut trailers = HeaderMap::new();
trailers.insert("zomg", "hello".parse().unwrap());
let (response, mut stream) = client.send_request(request, false).unwrap();
// send trailers
stream.send_trailers(trailers).unwrap();
// Spawn a task to run the conn...
tokio::spawn(h2.map_err(|e| println!("GOT ERR={:?}", e)));
response
.and_then(|response| {
println!("GOT RESPONSE: {:?}", response);
// Get the body
let (_, body) = response.into_parts();
Process {
body,
trailers: false,
}
})
.map_err(|e| {
println!("GOT ERR={:?}", e);
})
});
tokio::run(tcp);
}