I'm trying to write a TCP client to print incoming messages. I came up with the following code:
extern crate bytes;
extern crate futures;
extern crate tokio_core;
extern crate tokio_io;
use futures::Future;
use tokio_core::net::TcpStream;
use tokio_core::reactor::Core;
use tokio_io::AsyncRead;
use bytes::BytesMut;
fn main() {
let mut core = Core::new().unwrap();
let handle = core.handle();
let connection = TcpStream::connect(&"127.0.0.1:8081".parse().unwrap(), &handle);
let server = connection.and_then(move |mut stream| {
let mut buf = BytesMut::with_capacity(1000);
stream
.read_buf(&mut buf)
.map(|buf| print!("Buffer {:?}", buf))
.map_err(|e| eprintln!("Error: {}", e));
Ok(())
});
core.run(server).unwrap();
}
It compiles but it fails with a Buffer NotReady
error.
Rust is a compiled language, which means that you should pay attention to the warnings that the compiler generates:
warning: unused `std::result::Result` which must be used
--> src/main.rs:20:9
|
20 | / stream
21 | | .read_buf(&mut buf)
22 | | .map(|buf| print!("Buffer {:?}", buf))
23 | | .map_err(|e| eprintln!("Error: {}", e));
| |____________________________________________________^
|
= note: #[warn(unused_must_use)] on by default
Additionally, tokio has an entire chapter dedicated to low-level IO which I'll assume you've read to not bore you with details you already know.
First we take the connection
Future
and convert it into a Stream
. A stream can yield multiple values — in this case we return one value for every successful read. We create AsWeGetIt
for the simplest implementation of this.
We then print out each value of the stream using Stream::for_each
. Conveniently, this performs the corresponding conversion back to a Future
, which is what is needed for and_then
.
extern crate bytes;
extern crate futures;
extern crate tokio_core;
extern crate tokio_io;
use futures::{Future, Poll, Stream};
use tokio_core::net::TcpStream;
use tokio_core::reactor::Core;
use tokio_io::AsyncRead;
use bytes::BytesMut;
struct AsWeGetIt<R>(R);
impl<R> Stream for AsWeGetIt<R>
where
R: AsyncRead,
{
type Item = BytesMut;
type Error = std::io::Error;
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
let mut buf = BytesMut::with_capacity(1000);
self.0
.read_buf(&mut buf)
.map(|async| async.map(|_| Some(buf)))
}
}
fn main() {
let mut core = Core::new().unwrap();
let handle = core.handle();
let address = "127.0.0.1:8081".parse().expect("Unable to parse address");
let connection = TcpStream::connect(&address, &handle);
let client = connection
.and_then(|tcp_stream| {
AsWeGetIt(tcp_stream).for_each(|buf| {
println!("Buffer {:?}", buf);
Ok(())
})
})
.map_err(|e| eprintln!("Error: {}", e));
core.run(client).expect("Unable to run the event loop");
}