最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

rust - Peek tokio TcpStream is blocked - Stack Overflow

programmeradmin5浏览0评论

I edited the original question cause I found a simpler reproduction.

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let ln = TcpListener::bind(("0.0.0.0", 6789)).await?;

    // start an echo client
    tokio::spawn(async move {
        let mut connector = TcpStream::connect(("127.0.0.1", 6789)).await.unwrap();
        connector.write(b"a").await.unwrap();

        let mut buf = [0; 10];
        loop {
            // consume
            if let Ok(n) = connector.read(&mut buf).await {
                connector.write(&buf[..n]).await.unwrap();
            } else {
                break;
            }
        }
    });


    loop {
        let (io, _) = ln.accept().await?;

        tokio::spawn(async move {
            if let Err(e) = handle(io).await {
                println!("Connection error: {}", e);
            }
        });
    }
}

async fn handle(io: TcpStream) -> anyhow::Result<()> {
    let mut io = io;
    let mut buf = [0; 1];

    io.read(&mut buf).await?;
    println!("server received: {:?}", buf); // a
    io.write(b"b").await?;

    // io.read_exact(&mut buf).await?;
    io.peek(&mut buf).await?;
    println!("server received: {:?}", buf); // expect b but blocked

    Ok(())
}

It will blocked when call peek.

But read can work.

    // ...
    io.read_exact(&mut buf).await?;
    // io.peek(&mut buf).await?;
    println!("server received: {:?}", buf); // print b
    // ...
发布评论

评论列表(0)

  1. 暂无评论