TCP streams and framing
Quick answer
TCP provides an ordered byte stream, not a sequence of application messages. Define a framing rule so the receiver knows where each message ends.
Read exactly one frame
A single read can return fewer bytes than requested or combine pieces of multiple writes. A two-byte big-endian length prefix followed by that many bytes is one framing scheme. Check the length against a limit before allocating. A short header or body is a truncated frame; after a framing failure close the connection rather than guessing where to resume. These Cursor fixtures simulate the bytes without opening a socket.
use std::io::{self, Read, Cursor};fn frame(r: &mut impl Read) -> io::Result<Vec<u8>> { let mut h = [0; 2]; r.read_exact(&mut h)?; let n = u16::from_be_bytes(h) as usize; if n > 1024 { return Err(io::ErrorKind::InvalidData.into()); } let mut body = vec![0; n]; r.read_exact(&mut body)?; Ok(body)}fn main() { let mut r = Cursor::new(b"\0\x03cat\0\x03dog"); println!("{}", String::from_utf8(frame(&mut r).unwrap()).unwrap());}Expected stdout (not executed):
catThe reader stops before the next header.
use std::io::{Read, Cursor};fn main() { let mut r = Cursor::new(b"hi"); let mut body = [0; 3]; println!("{:?}", r.read_exact(&mut body).unwrap_err().kind());}Expected stdout (not executed):
UnexpectedEofThe receiver cannot accept a partially read frame.
Common mistake
Do not treat one TCP read as one application message.
Try it yourself
Extend the decoder test to read both frames and reject an oversized length.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
TCP streams and framing — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
A TCP frame claims 200 bytes but only 100 arrive before EOF. What should the decoder report?
TCP streams and framing — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust use std::io::{self, Read, Cursor}; fn frame(r: &mut impl Read) -> io::Result<Vec<u8>> { let mut h = [0; 2]; r.read_exact(&mut h)?; let n = u16::from_be_bytes(h) as usize; if n > 1024 { return Err(io::ErrorKind::InvalidData.into()); } let mut body = vec![0; n]; r.read_exact(&mut body)?; Ok(body) } fn main() { let mut r = Cursor::new(b"\0\x03cat\0\x03dog"); println!("{}", String::from_utf8(frame(&mut r).unwrap()).unwrap()); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
TCP streams and framing — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust use std::io::{Read, Cursor}; fn main() { let mut r = Cursor::new(b"hi"); let mut body = [0; 3]; println!("{:?}", r.read_exact(&mut body).unwrap_err().kind()); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.