← Questions
Read whole messages from a socket stream
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Apple's technical phone screen, last asked Sep 2025. It tests networking, parsing and buffers.
TCP delivers a stream of bytes, not messages. A single recv(k) may return part of a message, several messages, or nothing at all. Write a reader that turns the stream into whole messages, in two framing variants.
Interface
Unless you agree on a different interface with the interviewer, assume:
- The reader wraps a socket with
recv(k: int) -> bytes, which returns between 0 andkbytes;b""means the peer closed the connection. - Variant A, length-prefixed: each message is a 4-byte big-endian unsigned length followed by that many bytes.
read_message() -> bytes | Nonereturns exactly one message per call, orNoneat a clean end of stream. - Variant B, newline-delimited:
read_line() -> str | Nonereturns the next line without its\n, orNoneat end of stream. - Both keep an internal buffer across calls.
Example
Variant A, with recv returning these chunks in turn:
b"\x00\x00"
b"\x00\x02hi\x00\x00\x00\x03ab"
b"c"
b""
read_message() -> b"hi" # the header was split across two reads
read_message() -> b"abc" # its body was split across two reads
read_message() -> None # clean end of stream
Constraints
- Messages may be empty (length 0) or large; set a maximum message size.
- End of stream in the middle of a header or body is an error, not a clean close.
Clarifying questions
- What should happen on end of stream with a partial message buffered?
- Is there a maximum message size, and what happens above it?
- Is the socket blocking? Are timeouts needed?
- In variant B, is
\r\npossible, and is a final line without\nvalid?
What a strong answer covers
- A buffer plus a loop that calls
recvuntil enough bytes are present, then slices off exactly one message and keeps the rest. - Avoiding O(n^2) copying: a
bytearraywith a read offset, or a deque of chunks. - Rejecting oversized lengths before allocating, so a bad header can't exhaust memory.
- Distinguishing a clean close from a truncated message; handling timeouts and interrupted calls.
- Unit tests with a fake socket that returns scripted chunks: one byte at a time, many messages in one chunk, zero-length messages, truncation.
Follow-ups
- Make it non-blocking for use with an event loop.
- Write the matching sender, and handle partial sends.
- Support a protocol where the length is a variable-length integer.
Where it's asked
- Apple · Technical phone screen · Last asked Sep 2025
What it tests
networking · parsing · buffers
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
