如何在不使用tokio_proto包的情况下从tokio TCP连接中读取?

时间:2017-10-19 18:54:41

标签: rust rust-tokio

我正在尝试编写TCP客户端来打印传入的消息。我想出了以下代码:

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();
}

它编译但失败并出现Buffer NotReady错误。

1 个答案:

答案 0 :(得分:3)

Rust是一种编译语言,这意味着你应该注意编译器生成的警告:

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

另外,tokio has an entire chapter dedicated to low-level IO我认为你已经阅读过这些内容,而不是你已经知道的细节。

首先,我们将connection Future转换为Stream。流可以产生多个值 - 在这种情况下,我们为每次成功读取返回一个值。我们为最简单的实现创建了AsWeGetIt

然后我们使用Stream::for_each打印出流的每个值。方便地,这会执行相应的转换回Future,这是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"); }

InputFormat