expression

Async TCP read_exact and write_all

Use write_all for a complete fixed-size payload and read_exact for the agreed number of bytes. TCP itself does not preserve application message boundaries. Tokio is an external crate. Authorized isolated IPv4 loopback fixture; no public network or DNS. Expected stdout (not executed): book Common mistake: Assuming a single read returns the whole message.

Formal Syntax & Structure

rust syntaxrust
AsyncWriteExt::write_all; AsyncReadExt::read_exact

Working Example

Example Snippetrust
#[tokio::main(flavor = "current_thread")]async fn main() {    tokio::time::timeout(std::time::Duration::from_secs(3), async {        use tokio::net::{TcpListener, TcpStream};        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();        let addr = listener.local_addr().unwrap();        let (client, accepted) = tokio::join!(TcpStream::connect(addr), listener.accept());        let mut client = client.unwrap();        let (mut server, _) = accepted.unwrap();        use tokio::io::{AsyncReadExt, AsyncWriteExt};        client.write_all(b"book").await.unwrap();        let mut buf = [0; 4];        server.read_exact(&mut buf).await.unwrap();        println!("{}", std::str::from_utf8(&buf).unwrap());    }).await.expect("fixture deadline");}
Rust Reference