Socket Reader II
You are given a connected TCP socket. socket.recv(k) returns at most k bytes — possibly fewer, possibly just one — and returns an empty result once the peer has closed the connection (EOF). A message can arrive split across many recv calls, and one recv can contain several messages back to back.
Build MessageReader(socket, maxSize) on top of it, keeping an internal buffer between calls. Every message is a 4-byte big-endian unsigned length followed by that many payload bytes. readMessage() returns exactly one payload per call (as bytes), in order.
- A zero-length message is valid and returns an empty payload — which is not the same as EOF.
- At a clean EOF, with nothing buffered between messages, return
null. - EOF in the middle of a header or a payload is an error: throw.
- A header announcing more than
maxSizebytes is an error: throw before trying to read the payload.
stream: 00 00 00 05 h e l l o 00 00 00 00 chunks arrive as [00 00] [00 05 h e] [l l o 00 00 00 00] readMessage() -> "hello", readMessage() -> "" (empty payload), readMessage() -> null
The harness feeds your reader from a fake socket that fragments the stream at chosen offsets, calls readMessage a fixed number of times, and records each result — "error" for a throw. Results longer than 32 characters are shown as len:N:head:tail.
Hints
Hint 1
Loop: while the buffer does not yet hold a complete frame, call recv and append; when recv returns nothing, decide whether the buffer is empty (clean EOF) or holds a partial frame.
Hint 2
Wait for 4 bytes, decode them as a big-endian unsigned integer, check the limit, then wait for 4 + length bytes before consuming anything. Never assume one recv equals one message.