Help to clean tokio spawn future

async fn main() -> Result<(), Box<dyn Error>> {
    // Allow passing an address to listen on as the first argument of this
    // program, but otherwise we'll just set up our TCP listener on
    // for connections.
    let addr = env::args()
        .unwrap_or_else(|| "".to_string());

    // Next up we create a TCP listener which will listen for incoming
    // connections. This TCP listener is bound to the address we determined
    // above and must be associated with an event loop.
    let listener = TcpListener::bind(&addr).await?;
    println!("Listening on: {}", addr);

    loop {
        // Asynchronously wait for an inbound socket.
        let (mut socket, _) = listener.accept().await?;

        // And this is where much of the magic of this server happens. We
        // crucially want all clients to make progress concurrently, rather than
        // blocking one on completion of another. To achieve this we use the
        // `tokio::spawn` function to execute the work in the background.
        // Essentially here we're executing a new task to run concurrently,
        // which will allow all of our clients to be processed concurrently.

        tokio::spawn(async move {
            let mut buf = vec![0; 1024];

            // In a loop, read data from the socket and write the data back.
            loop {
                let n = socket
                    .read(&mut buf)
                    .expect("failed to read data from socket");

                if n == 0 {

                    .expect("failed to write data to socket");

Here`s the example of tokio.
How to detect client has closed the connect?
I think the spawn future is blocking or alive when client connect closed.
How to clean the future? :grinning:

markdown please Markdown Cheatsheet · adam-p/markdown-here Wiki · GitHub

If the client closes the connection, then the read call returns zero and your code correctly returns from the loop.

1 Like


Yes. I thought the Err(e) should be matched when client closed.

Thanks a lot.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.