no method named `incoming` found for struct `tokio::net::TcpListener`

817 views Asked by At

I am writing a tcp echo server using tower and tokio. However, I am unable to use the method incoming for 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
        });
    }
}
1

There are 1 answers

1
Chayim Friedman On BEST ANSWER

You're unable to use it because it doesn't exist. Only std's TcpListener has incoming() - tokio's has 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
        });
    }
}