rust 没有为结构时雄::net::TcpListener找到名为“incoming”的方法

vuktfyat  于 2023-01-21  发布在  其他
关注(0)|答案(1)|浏览(172)

我正在使用tower和时雄编写一个tcp echo服务器,但是我无法使用incoming方法来实现tokio::net::TcpListener

/*
[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
        });
    }
}
huus2vyu

huus2vyu1#

您无法使用它,因为它不存在。只有std的TcpListenerincoming()-时雄的有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
        });
    }
}

相关问题