1

我正在尝试编写一个 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错误。

4

1 回答 1

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 有一整章专门介绍低级 IO,我假设您已经阅读了这些章节,不会对您已经知道的细节感到厌烦。

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

然后我们使用 打印出流的每个值Stream::for_each。方便的是,这会执行相应的转换回 a 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");
}
于 2017-10-21T15:25:20.163 回答