我正在使用tower和tokio编写一个tcp echo服务器。但是,我无法对tokio::net::TcpListener
incoming
方法。/*
[dependencies]
futures = "0.3"
tokio = { version = "1", features = ["full"] }
tower = { version = "0.4", features = ["full"] }
*/
use tokio::net::TcpListener;
use tower::Service;
use futures::future;
use std::task::{Context,Poll};
struct Echo;
impl Service<Vec<u8>> for Echo {
type Response = Vec<u8>;
type Error = std::io::Error;
type Future = future::Ready<Result<Self::Response, Self::Error>>;
fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn call(&mut self, req: Vec<u8>) -> Self::Future {
future::ok(req)
}
}
#[tokio::main]
async fn main() {
let addr = "127.0.0.1:8080".parse().unwrap();
let listener = TcpListener::bind(&addr).await.unwrap();
let mut incoming = listener.incoming();
while let Some(socket) = incoming.next().await {
let socket = socket.unwrap();
tokio::spawn(async move {
let (reader, writer) = socket.split();
let echo = Echo;
tower::service_fn(move |req| echo.call(req)).serve(reader, writer).await
});
}
}
您无法使用它,因为它不存在。只有std的TcpListener
有incoming()
- tokio的accept()
:
#[tokio::main]
async fn main() {
let addr = "127.0.0.1:8080".parse().unwrap();
let listener = TcpListener::bind(&addr).await.unwrap();
loop {
let socket = listener.accept().await;
let socket = socket.unwrap();
tokio::spawn(async move {
let (reader, writer) = socket.split();
let echo = Echo;
tower::service_fn(move |req| echo.call(req)).serve(reader, writer).await
});
}
}