作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试编写一个 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
错误。
最佳答案
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");
}
关于rust - 如何在不使用 tokio_proto crate 的情况下从 tokio TCP 连接读取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46836933/
在我的 SmtpService 中,我想立即发送响应 header ,并在处理完成时发送正文。这应该遵循 SMTP 交换: C: DATA S: 354 Start mail input C: ...
我正在尝试编写一个 TCP 客户端来打印传入的消息。我想出了以下代码: extern crate bytes; extern crate futures; extern crate tokio_cor
我是一名优秀的程序员,十分优秀!