Messages from a TCP stream
Reassemble length-prefixed messages from recv() chunks that split and merge them. A medium embedded C problem (Sockets API basics), run and graded in the…
medium · Sockets API basics · sockets · tcp · framing
TCP delivers a stream of bytes, not messages: one recv() may return half a message, or two and a bit. Applications therefore frame their messages. Here each message is a 2-byte big-endian length followed by that many bytes.
Write feed(r, data, n), called with each chunk recv() returns: append it to the reader's buffer, then call on_message() for every complete message now in the buffer, and keep any incomplete remainder for the next call. Messages are at most 60 bytes.
Starter code
void feed(reader_t *r, const uint8_t *data, int n) {
(void)r;
int len = (data[0] << 8) | data[1];
on_message(data + 2, len);
(void)n;
}Example tests
One message per chunk
reader_t r = {0};
uint8_t a[] = { 0, 5, 'h', 'e', 'l', 'l', 'o' };
feed(&r, a, 7);Expected output:
message (5): helloTwo messages in one chunk
reader_t r = {0};
uint8_t a[] = { 0, 2, 'h', 'i', 0, 3, 'y', 'o', 'u' };
feed(&r, a, 9);Expected output:
message (2): hi
message (3): youLearn it first
- Sockets API basics · Socket lifecycle, TCP versus UDP, blocking and select/poll.