我正在尝试使用未来的请求运行具有异步响应的超级服务器。当 future 的poll
方法被调用并返回Async::NotReady
时,连接就被断开了(“dropping I/O source: 0”)。我预计该poll
方法会被多次调用,直到它返回Async::Ready
。
显示的示例返回一个异步 io 未来,它正在做(我猜)同样的事情。
为什么future的poll
函数只调用一次,为什么在future返回后hyper会断开连接Async::NotReady
?
示例代码:(超版本为:v0.12.21)
use futures::{Async, Future, Poll};
use hyper::http::{Request, Response};
use hyper::service::service_fn;
use hyper::{Body, Server};
fn main() {
let addr = ([127, 0, 0, 1], 3335).into();
println!("Start request handler. (Listening on http://{})", addr);
hyper::rt::run(
Server::bind(&addr)
.serve(|| service_fn(|request: Request<Body>| handle_request(request.uri().path())))
.map_err(|e| println!("server error: {}", e)),
);
}
type BoxedResponseFuture = Box<Future<Item = Response<Body>, Error = tokio::io::Error> + Send>;
fn handle_request(path: &str) -> BoxedResponseFuture {
println!("Handle request {:?}", path);
Box::new(
ResponseFuture { ready: false }
.and_then(|_| {
let response = Response::new(Body::from("Success".to_string()));
Ok(response)
})
.or_else(|e| {
let response = Response::new(Body::from(format!("Error: {:?}", e)));
Ok(response)
}),
)
}
struct ResponseFuture {
ready: bool,
}
impl Future for ResponseFuture {
type Item = ();
type Error = ();
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
println!("Poll future");
if self.ready {
println!("Future ready");
return Ok(Async::Ready(()));
}
println!("Future not ready");
self.ready = true;
Ok(Async::NotReady)
}
}