Frame messages over a TCP byte stream
Frame messages over a TCP byte stream
TCP does not preserve write boundaries. A read may return part of a message or bytes from multiple messages. Framing defines how a receiver knows where a message ends. A length prefix is one common format: read the header fully, validate length before allocation, then read the body fully. The next examples use in-memory readers to reproduce fragmentation without network timing.
package main
import ( "encoding/binary" "errors" "fmt" "io" "strings")
func frame(r io.Reader) (string, error) { var h [2]byte if _, e := io.ReadFull(r, h[:]); e != nil { return "", e } n := int(binary.BigEndian.Uint16(h[:])) if n > 16 { return "", errors.New("frame too large") } p := make([]byte, n) _, e := io.ReadFull(r, p) return string(p), e}func main() { r := io.MultiReader(strings.NewReader("\x00"), strings.NewReader("\x03A"), strings.NewReader("BC\x00\x02OK")) for i := 0; i < 2; i++ { s, e := frame(r) if e != nil { panic(e) } fmt.Println(s) }}Two header bytes encode an unsigned length in big-endian order (most significant byte first). ReadFull crosses the artificial fragment boundaries. Limit payloads to 16 bytes in this toy protocol before allocation. In a real connection, reject malformed or truncated frames and close if framing cannot be recovered.
Expected output:
ABCOKReject truncated frames
package main
import ( "encoding/binary" "errors" "fmt" "io" "strings")
func frame(r io.Reader) (string, error) { var h [2]byte if _, e := io.ReadFull(r, h[:]); e != nil { return "", e } n := int(binary.BigEndian.Uint16(h[:])) if n > 16 { return "", errors.New("frame too large") } p := make([]byte, n) _, e := io.ReadFull(r, p) return string(p), e}func main() { _, e := frame(strings.NewReader("\x00\x04ab")) fmt.Println(errors.Is(e, io.ErrUnexpectedEOF)) _, e = frame(strings.NewReader("\x00\x11")) fmt.Println(e)}An incomplete payload is not a valid message. EOF before any header byte can be normal end-of-stream, but a truncated header or payload is a protocol failure (even when the body read reports EOF with no bytes). A sender should check write counts and errors; avoid concurrent writers interleaving frames without serialization.
Expected output:
trueframe too largeTry it locally
Read a one-byte length header then at most eight payload bytes with ReadFull. Decode the frame \x03cat and print cat.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Networking 04: Frame messages over a TCP byte stream
Check the lesson objective before moving on.
Why read a length header with ReadFull?
When should the receiver validate payload length?