How can use bytes to read data from tokio TcpStream

i am trying to use BytesMut to read data from TcpStream, but its always empty

    let mut buf = BytesMut::with_capacity(1024);
    let req = b"GET /Chunked HTTP/1.1\r\n\r\n";
    let mut tcp_stream = TcpStream::connect("anglesharp.azurewebsites.net:80").await?;

    tcp_stream.write_all(req).await?;

    let mut reader = BufReader::new(tcp_stream);
    reader.read(&mut buf).await?;

    println!("{:?}", buf);

This is because read wants a slice, and &mut buf on a BytesMut gives you a slice over the data that was already written (an empty slice). You want to use read_buf instead.

1 Like