expression

Reject a truncated TCP frame

A peer closing before a fixed-size record is complete causes read_exact to fail. Do not process the partially updated buffer as a complete record. Tokio is an external crate. Authorized isolated IPv4 loopback fixture; no public network or DNS. Expected stdout (not executed): true Common mistake: Decoding the whole buffer after a failed read_exact.

Formal Syntax & Structure

rust syntaxrust
read_exact; ErrorKind::UnexpectedEof

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"a").await.unwrap();        client.shutdown().await.unwrap();        let mut b = [0; 2];        let err = server.read_exact(&mut b).await.unwrap_err();        println!("{}", err.kind() == std::io::ErrorKind::UnexpectedEof);    }).await.expect("fixture deadline");}
Rust Reference