Skip to content

WebSocket Extended Payload Lengths in C++

A 126-byte text does not fit the short-frame format. Extend the same raw-socket client to read and write larger WebSocket frames, without letting a peer's advertised length choose your memory budget.

Before you start

Complete Ping and Pong. Run these commands on the Pi from the examples repository's network/ directory. The C++ file still uses direct Linux sockets and OpenSSL Crypto for the handshake nonce/hash and frame masks; no socket wrapper or new dependency is introduced.

Outcome: exchange a 65,536-byte ASCII text in a single frame, decode its eight-byte length field, and reject invalid or oversized lengths before waiting for their bodies.

This is still a reduced plaintext loopback client: one exact text echo, one correlated Ping, binary-safe control replies and Close 1000. Fragmentation, general UTF-8, arbitrary Close handling and full protocol-error Close replies remain outside this lesson. It is not wss:// or a production endpoint.

Three WebSocket length formats

The low seven bits of the second header byte are either the length itself or a marker telling you how many length bytes follow.

Payload bytes Seven-bit marker Following length bytes Unmasked server prefix
0–125 Actual length None 125 bytes: 81 7d
126–65,535 126 Two, big-endian 126 bytes: 81 7e 00 7e
65,536 and above 127 Eight, big-endian, top bit zero 65,536 bytes: 81 7f 00 00 00 00 00 01 00 00

These prefixes describe final text frames with RSV bits clear. The last row describes the protocol's length encoding, not this sample's accepted size range: our maximum is exactly 65,536 bytes (64 KiB).

The shortest applicable format is required. Encoding 125 as marker 126 followed by 00 7d is invalid even though the decoded number is small. Encoding 65,535 with marker 127 is invalid for the same reason. See RFC 6455 framing.

For client frames, set the MASK bit in that second byte and put the four-byte mask after any extended length bytes, before the payload. The payload length excludes the mask and all header bytes. For example, a masked 126-byte text begins 81 fe 00 7e, then the mask, then 126 masked bytes.

Validate before trusting the size

flowchart TD accTitle: Length metadata is not permission to allocate accDescr: Read two header bytes and validate flags, masking and control length. Read zero, two or eight extended bytes. Reject nonminimal encodings and a set high bit. Reject values above 65536 before converting to size_t or waiting for the body. Only then read and dispatch the complete bounded frame. H[Read two header bytes] --> V{Allowed flags, mask and control length?} V -->|No| X[Abort reduced teaching session] V -->|Yes| E[Read zero, two or eight length bytes] E --> C{Canonical encoding and high bit clear?} C -->|No| X C -->|Yes| L{Length at most 65536?} L -->|No| X L -->|Yes| B[Convert size, read bounded body] B --> D[Dispatch text or control frame]

Decode into std::uint64_t, checking the 64-bit field's top bit before the shift loop. Build the number with unsigned bytes and advertised = (advertised << 8) | byte; casting a signed char directly could sign-extend bytes such as ff.

Check canonical encoding and the application limit before converting to std::size_t, adding the header size or waiting for the advertised body. Do not resize(advertised) or allocate from an unchecked peer value. A huge but otherwise correctly encoded length is outside our policy, not necessarily outside the protocol.

The parser waits for a complete length field even when TCP splits its bytes across reads. Conversely, a receive can contain a complete frame plus the next frame's prefix: remove only the consumed bytes from pending.

Run all three formats

Build the new client:

cmake --preset native-debug
cmake --build --preset native-debug --target ws_lengths_client --parallel 2

Terminal A:

timeout 35s python3 fixtures/ws_lengths.py 9007

After LISTEN 9007, terminal B:

./build/native/debug/ws_lengths_client 9007 65536

Expected output:

1
2
3
echo_bytes=65536
matched_pong=yes pings_replied=1 pongs_ignored=0
close=1000 tcp_eof=yes

The client generates a repeating abcdefghijklmnopqrstuvwxyz ASCII pattern and requires an exact echo, not just the same byte count. It prints a summary instead of flooding your terminal with 64 KiB of text. The fixture checks the masked text, sends a binary Ping, then returns the matching Pong and text echo before the normal Close exchange.

Restart terminal A for each new run. Try these commands one at a time against a fresh fixture:

1
2
3
4
./build/native/debug/ws_lengths_client 9007 125
./build/native/debug/ws_lengths_client 9007 126
./build/native/debug/ws_lengths_client 9007 65535
./build/native/debug/ws_lengths_client 9007 65536

The first number is the port; the second is the generated payload's byte count, not a message string as in the preceding lesson. Omitting it selects 256 bytes; zero selects empty text. An optional final session_ms accepts 1–10000, with a default of 3000.

Use the new fixture: the previous short-frame server cannot decode an extended-length text.

Control frames do not get larger

The encoder chooses the shortest format for text and adds a fresh random mask for every client frame. The XOR index starts at payload byte zero, not at the start of the header or extended length.

Ping, Pong and Close still have a maximum payload of 125 bytes and cannot be fragmented. Our reader rejects a control frame with marker 126 or 127 from its first two bytes, without waiting for an extended field. Increasing the text limit must not silently relax the control rules. See RFC 6455 control frames.

The previous control dispatcher is retained: binary Pings receive identical masked Pongs, unrelated Pongs are ignored, and the echo and matching Pong complete independently. In-flight controls are handled while waiting for peer Close.

A Ping cannot interrupt the middle of one frame's payload: those bytes belong to that frame. Fragmentation, covered next, allows a message to span frames with controls between them.

Read the standalone C++ implementation

Focus on send_frame and read_frame: marker selection, big-endian shifts, the position of the mask, and validation before the body wait. The handshake and raw socket, connect, poll, send, recv and explicit close stay in this one file.

Full standalone client: app/ws-lengths/client.cpp
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
#include <algorithm>
#include <arpa/inet.h>
#include <array>
#include <cerrno>
#include <charconv>
#include <chrono>
#include <cstdint>
#include <iostream>
#include <map>
#include <openssl/evp.h>
#include <openssl/rand.h>
#include <poll.h>
#include <stdexcept>
#include <string>
#include <string_view>
#include <sys/socket.h>
#include <system_error>
#include <unistd.h>
#include <utility>

int main(int argc, char** argv) {
    int fd = -1;
    int status = 0;
    try {
        if (argc < 2 || argc > 4) {
            throw std::invalid_argument(
                "usage: ws_lengths_client port [payload_bytes [session_ms]]");
        }
        unsigned int port = 0;
        const std::string_view text = argv[1];
        const auto [end, invalid] =
            std::from_chars(text.data(), text.data() + text.size(), port);
        if (invalid != std::errc{} || end != text.data() + text.size() ||
            port == 0 || port > 65535) {
            throw std::invalid_argument("port must be 1..65535");
        }
        constexpr std::uint64_t payload_limit = 65536;
        unsigned int payload_bytes = 256;
        if (argc >= 3) {
            const std::string_view count = argv[2];
            const auto [last, error] = std::from_chars(
                count.data(), count.data() + count.size(), payload_bytes);
            if (error != std::errc{} || last != count.data() + count.size() ||
                payload_bytes > payload_limit) {
                throw std::invalid_argument("payload_bytes must be 0..65536");
            }
        }
        // Predictable printable text, without a huge command-line argument.
        std::string message(payload_bytes, 'x');
        for (std::size_t i = 0; i < message.size(); ++i) {
            message[i] = static_cast<char>('a' + i % 26);
        }
        int session_ms = 3000;
        if (argc == 4) {
            const std::string_view budget = argv[3];
            const auto [last, error] = std::from_chars(
                budget.data(), budget.data() + budget.size(), session_ms);
            if (error != std::errc{} || last != budget.data() + budget.size() ||
                session_ms < 1 || session_ms > 10000) {
                throw std::invalid_argument("session_ms must be 1..10000");
            }
        }
        std::array<unsigned char, 16> nonce{};
        std::array<unsigned char, 25> encoded_key{};
        if (RAND_bytes(nonce.data(), nonce.size()) != 1 ||
            EVP_EncodeBlock(encoded_key.data(), nonce.data(), nonce.size()) !=
                24) {
            throw std::runtime_error("cannot generate WebSocket key");
        }
        const std::string key(reinterpret_cast<const char*>(encoded_key.data()),
                              24);
        const std::string challenge =
            key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
        std::array<unsigned char, EVP_MAX_MD_SIZE> digest{};
        std::size_t digest_size = 0;
        std::array<unsigned char, 29> encoded_accept{};
        if (EVP_Q_digest(nullptr, "SHA1", nullptr, challenge.data(),
                         challenge.size(), digest.data(), &digest_size) != 1 ||
            digest_size != 20 ||
            EVP_EncodeBlock(encoded_accept.data(), digest.data(), 20) != 28) {
            throw std::runtime_error("cannot compute WebSocket accept value");
        }
        const std::string expected_accept(
            reinterpret_cast<const char*>(encoded_accept.data()), 28);
        fd = ::socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
        if (fd < 0) {
            throw std::system_error(errno, std::generic_category(), "socket");
        }
        const auto deadline = std::chrono::steady_clock::now() +
                              std::chrono::milliseconds(session_ms);
        const auto check_deadline = [&] {
            if (std::chrono::steady_clock::now() >= deadline) {
                throw std::runtime_error("session deadline expired");
            }
        };
        const auto wait_for = [&](short events) {
            for (;;) {
                check_deadline();
                const auto remaining =
                    std::chrono::ceil<std::chrono::milliseconds>(
                        deadline - std::chrono::steady_clock::now())
                        .count();
                if (remaining <= 0) {
                    throw std::runtime_error("session deadline expired");
                }
                pollfd ready{fd, events, 0};
                const int result =
                    ::poll(&ready, 1, static_cast<int>(remaining));
                if (result < 0 && errno == EINTR) {
                    continue;
                }
                if (result < 0) {
                    throw std::system_error(errno, std::generic_category(),
                                            "poll");
                }
                check_deadline();
                if (result > 0) {
                    return; // The next socket operation inspects EOF/errors.
                }
            }
        };
        const auto send_bytes = [&](std::string_view bytes) {
            std::size_t offset = 0;
            while (offset < bytes.size()) {
                check_deadline();
                const auto sent = ::send(fd, bytes.data() + offset,
                                         bytes.size() - offset, MSG_NOSIGNAL);
                if (sent < 0 && (errno == EAGAIN || errno == EWOULDBLOCK ||
                                 errno == EINTR)) {
                    wait_for(POLLOUT);
                    continue;
                }
                if (sent <= 0) {
                    throw std::runtime_error("send failed");
                }
                offset += static_cast<std::size_t>(sent);
            }
        };
        sockaddr_in server{};
        server.sin_family = AF_INET;
        server.sin_port = htons(static_cast<std::uint16_t>(port));
        server.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
        if (::connect(fd, reinterpret_cast<const sockaddr*>(&server),
                      sizeof(server)) < 0) {
            if (errno != EINPROGRESS) {
                throw std::system_error(errno, std::generic_category(),
                                        "connect");
            }
            wait_for(POLLOUT);
            int socket_error = 0;
            socklen_t size = sizeof(socket_error);
            if (::getsockopt(fd, SOL_SOCKET, SO_ERROR, &socket_error, &size) <
                0) {
                throw std::system_error(errno, std::generic_category(),
                                        "getsockopt");
            }
            if (socket_error != 0) {
                throw std::system_error(socket_error, std::generic_category(),
                                        "connect");
            }
        }
        const std::string request =
            "GET /ws HTTP/1.1\r\nHost: localhost:" + std::to_string(port) +
            "\r\nUpgrade: websocket\r\nConnection: "
            "Upgrade\r\nSec-WebSocket-Key: " +
            key + "\r\nSec-WebSocket-Version: 13\r\n\r\n";
        send_bytes(request);
        // Do not shutdown(SHUT_WR): this same connection would carry frames.
        std::string response;
        std::array<char, 64> buffer{};
        std::size_t boundary = std::string::npos;
        while (boundary == std::string::npos) {
            check_deadline();
            const auto count = ::recv(fd, buffer.data(), buffer.size(), 0);
            if (count < 0 &&
                (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)) {
                wait_for(POLLIN);
                continue;
            }
            if (count <= 0) {
                throw std::runtime_error(
                    "handshake ended before complete headers");
            }
            response.append(buffer.data(), static_cast<std::size_t>(count));
            boundary = response.find("\r\n\r\n");
            if ((boundary == std::string::npos && response.size() > 4096) ||
                (boundary != std::string::npos && boundary + 4 > 4096)) {
                throw std::runtime_error("handshake headers exceed 4096 bytes");
            }
        }
        const auto trim = [](std::string_view value) {
            while (!value.empty() &&
                   (value.front() == ' ' || value.front() == '\t')) {
                value.remove_prefix(1);
            }
            while (!value.empty() &&
                   (value.back() == ' ' || value.back() == '\t')) {
                value.remove_suffix(1);
            }
            return value;
        };
        const auto lower = [](std::string value) {
            for (char& c : value) {
                if (c >= 'A' && c <= 'Z') {
                    c += 'a' - 'A';
                }
            }
            return value;
        };
        const auto token_char = [](unsigned char c) {
            return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
                   (c >= '0' && c <= '9') ||
                   std::string_view("!#$%&'*+-.^_`|~").find(c) !=
                       std::string_view::npos;
        };
        const auto first_end = response.find("\r\n");
        const std::string_view status_line(response.data(), first_end);
        if (status_line.size() < 13 ||
            !status_line.starts_with("HTTP/1.1 101 ") ||
            !std::all_of(status_line.begin(), status_line.end(),
                         [](unsigned char c) {
                             return c == '\t' || (c >= 32 && c < 127);
                         })) {
            throw std::runtime_error("expected HTTP/1.1 status 101");
        }
        std::map<std::string, std::string> fields;
        std::size_t cursor = first_end + 2;
        while (cursor < boundary) {
            const auto line_end = response.find("\r\n", cursor);
            const std::string_view line(response.data() + cursor,
                                        line_end - cursor);
            const auto colon = line.find(':');
            if (colon == std::string_view::npos || colon == 0 ||
                !std::all_of(line.begin(), line.begin() + colon, token_char)) {
                throw std::runtime_error("invalid handshake header name");
            }
            const std::string name = lower(std::string(line.substr(0, colon)));
            const auto raw_value = line.substr(colon + 1);
            if (!std::all_of(raw_value.begin(), raw_value.end(),
                             [](unsigned char c) {
                                 return c == '\t' || (c >= 32 && c < 127);
                             })) {
                throw std::runtime_error("invalid handshake header value");
            }
            const auto value = trim(raw_value);
            if (name == "sec-websocket-protocol" ||
                name == "sec-websocket-extensions" ||
                name == "content-length" || name == "transfer-encoding") {
                throw std::runtime_error(
                    "unexpected negotiation or HTTP body framing");
            }
            if (name == "upgrade" || name == "connection" ||
                name == "sec-websocket-accept") {
                if (!fields.emplace(name, value).second) {
                    throw std::runtime_error("duplicate handshake field");
                }
            }
            cursor = line_end + 2;
        }
        if (!fields.contains("upgrade") || !fields.contains("connection") ||
            !fields.contains("sec-websocket-accept") ||
            lower(fields.at("upgrade")) != "websocket" ||
            fields.at("sec-websocket-accept") != expected_accept) {
            throw std::runtime_error(
                "invalid WebSocket upgrade or accept value");
        }
        bool upgrade_token = false;
        std::string_view options = fields.at("connection");
        for (;;) {
            const auto comma = options.find(',');
            const auto option = trim(options.substr(0, comma));
            if (option.empty() ||
                !std::all_of(option.begin(), option.end(), token_char)) {
                throw std::runtime_error("invalid Connection token list");
            }
            upgrade_token |= lower(std::string(option)) == "upgrade";
            if (comma == std::string_view::npos) {
                break;
            }
            options.remove_prefix(comma + 1);
        }
        if (!upgrade_token) {
            throw std::runtime_error("Connection lacks Upgrade token");
        }
        check_deadline();
        // Start with bytes received alongside the HTTP header terminator.
        std::string pending = response.substr(boundary + 4);
        const auto send_frame = [&](unsigned char opcode,
                                    std::string_view payload) {
            if (payload.size() > payload_limit ||
                (opcode >= 0x8 && payload.size() > 125)) {
                throw std::runtime_error("outgoing frame exceeds profile");
            }
            std::array<unsigned char, 4> mask{};
            if (RAND_bytes(mask.data(), mask.size()) != 1) {
                throw std::runtime_error("cannot generate frame mask");
            }
            std::string frame;
            frame.push_back(static_cast<char>(0x80 | opcode));
            const std::uint64_t size = payload.size();
            if (size <= 125) {
                frame.push_back(static_cast<char>(0x80 | size));
            } else {
                const int bytes = size <= 65535 ? 2 : 8;
                frame.push_back(
                    static_cast<char>(0x80 | (bytes == 2 ? 126 : 127)));
                for (int shift = (bytes - 1) * 8; shift >= 0; shift -= 8) {
                    frame.push_back(static_cast<char>((size >> shift) & 0xff));
                }
            }
            frame.append(reinterpret_cast<const char*>(mask.data()),
                         mask.size());
            for (std::size_t index = 0; index < payload.size(); ++index) {
                frame.push_back(static_cast<char>(
                    static_cast<unsigned char>(payload[index]) ^
                    mask[index % 4]));
            }
            send_bytes(frame);
        };
        const auto read_more = [&] {
            for (;;) {
                check_deadline();
                const auto count = ::recv(fd, buffer.data(), buffer.size(), 0);
                if (count < 0 && (errno == EAGAIN || errno == EWOULDBLOCK ||
                                  errno == EINTR)) {
                    wait_for(POLLIN);
                    continue;
                }
                if (count <= 0) {
                    throw std::runtime_error(
                        "TCP ended before a complete frame");
                }
                pending.append(buffer.data(), static_cast<std::size_t>(count));
                if (pending.size() > payload_limit + 10 + buffer.size()) {
                    throw std::runtime_error(
                        "frame buffer exceeds bounded read-ahead");
                }
                return;
            }
        };
        const auto read_frame = [&] {
            while (pending.size() < 2) {
                read_more();
            }
            const auto first = static_cast<unsigned char>(pending[0]);
            const auto second = static_cast<unsigned char>(pending[1]);
            if (first != 0x81 && first != 0x88 && first != 0x89 &&
                first != 0x8a) {
                throw std::runtime_error(
                    "expected final text/Close/Ping/Pong with RSV bits clear");
            }
            const unsigned char marker = second & 0x7f;
            if ((second & 0x80) != 0) {
                throw std::runtime_error("server frames must not be masked");
            }
            if ((first & 0x08) != 0 && marker > 125) {
                throw std::runtime_error(
                    "control payload must be at most 125 bytes");
            }
            const std::size_t extended = marker == 126   ? 2
                                         : marker == 127 ? 8
                                                         : 0;
            const std::size_t header = 2 + extended;
            while (pending.size() < header) {
                read_more();
            }
            std::uint64_t advertised = marker;
            if (extended != 0) {
                if (extended == 8 &&
                    (static_cast<unsigned char>(pending[2]) & 0x80) != 0) {
                    throw std::runtime_error(
                        "64-bit length has its high bit set");
                }
                advertised = 0;
                for (std::size_t i = 2; i < header; ++i) {
                    advertised = (advertised << 8) |
                                 static_cast<unsigned char>(pending[i]);
                }
                if ((extended == 2 && advertised < 126) ||
                    (extended == 8 && advertised < 65536)) {
                    throw std::runtime_error("nonminimal payload length");
                }
            }
            // Validate before narrowing, adding, allocating or waiting for
            // body.
            if (advertised > payload_limit) {
                throw std::runtime_error("payload exceeds 65536-byte policy");
            }
            const auto size = static_cast<std::size_t>(advertised);
            while (pending.size() < header + size) {
                read_more();
            }
            std::string payload = pending.substr(header, size);
            pending.erase(0, header + size);
            return std::pair{static_cast<unsigned char>(first & 15), payload};
        };
        std::array<unsigned char, 8> token_bytes{};
        if (RAND_bytes(token_bytes.data(), token_bytes.size()) != 1) {
            throw std::runtime_error("cannot generate Ping token");
        }
        const std::string ping_token(
            reinterpret_cast<const char*>(token_bytes.data()),
            token_bytes.size());
        bool pong_received = false;
        unsigned int ping_pong_count = 0;
        unsigned int pings_replied = 0;
        unsigned int pongs_ignored = 0;
        const auto handle_control = [&](unsigned char opcode,
                                        const std::string& payload) {
            if (opcode != 0x9 && opcode != 0xa) {
                return false;
            }
            if (++ping_pong_count > 32) {
                throw std::runtime_error("Ping/Pong frame budget exceeded");
            }
            if (opcode == 0x9) {
                // Preserve arbitrary bytes, including NUL, and mask our reply.
                send_frame(0xa, payload);
                ++pings_replied;
            } else if (!pong_received && payload == ping_token) {
                pong_received = true;
            } else {
                // A Pong can be unsolicited. Never reply to it with another
                // Pong.
                ++pongs_ignored;
            }
            return true;
        };
        send_frame(0x9, ping_token);
        send_frame(0x1, message);
        bool echo_received = false;
        std::string echo;
        while (!echo_received || !pong_received) {
            const auto [opcode, payload] = read_frame();
            if (handle_control(opcode, payload)) {
                continue;
            }
            if (opcode != 0x1 || echo_received || payload != message) {
                throw std::runtime_error(
                    "expected one exact ASCII text echo before Close");
            }
            echo = payload;
            echo_received = true;
        }
        const std::string normal_close{"\x03\xe8", 2};
        send_frame(0x8, normal_close);
        for (;;) {
            const auto [opcode, payload] = read_frame();
            // We sent Close but have not received it: Ping still needs Pong.
            if (handle_control(opcode, payload)) {
                continue;
            }
            if (opcode != 0x8 || payload != normal_close) {
                throw std::runtime_error(
                    "expected Close with code 1000 and no reason");
            }
            break;
        }
        if (!pending.empty()) {
            throw std::runtime_error("data after Close");
        }
        // This teaching client additionally waits for the server's TCP EOF.
        for (;;) {
            check_deadline();
            char extra = 0;
            const auto count = ::recv(fd, &extra, 1, 0);
            if (count < 0 &&
                (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)) {
                wait_for(POLLIN);
                continue;
            }
            if (count < 0) {
                throw std::system_error(errno, std::generic_category(),
                                        "recv after Close");
            }
            if (count > 0) {
                throw std::runtime_error("data after Close");
            }
            break;
        }
        std::cout << "echo_bytes=" << echo.size() << '\n'
                  << "matched_pong=yes pings_replied=" << pings_replied
                  << " pongs_ignored=" << pongs_ignored
                  << "\nclose=1000 tcp_eof=yes\n";
    } catch (const std::exception& error) {
        std::cerr << error.what() << '\n';
        status = 1;
    }
    if (fd >= 0) {
        ::close(fd);
    }
    return status;
}

Compile the source directly

To compile this one source without CMake, from the same network/ directory:

1
2
3
4
mkdir -p build/direct-ws-lengths
c++ -std=c++20 -Wall -Wextra -Wpedantic -Werror \
    app/ws-lengths/client.cpp -o build/direct-ws-lengths/ws_lengths_client \
    $(pkg-config --cflags --libs libcrypto)

Use ./build/direct-ws-lengths/ws_lengths_client 9007 65536 against a fresh fixture. OpenSSL supplies randomness and the Upgrade hash here, not transport encryption.

Keep memory, time and work bounded

The payload limit is 65,536 bytes. The pending buffer has a separate logical length cap of 65536 + 10 + 64 = 65610 bytes: maximum payload, maximum unmasked server header and one receive buffer of read-ahead. This is not a total process-memory limit. The generated message, outgoing encoded frame, parsed payload copies, handshake storage and library allocations also consume memory.

The same fixed session deadline covers connect through TCP EOF after local nonce/hash setup. Partial headers, slow payload bytes and successfully answered Pings do not renew it. The 32 incoming Ping/Pong limit still applies across both the echo and Close waits. A larger permitted text does not imply unlimited waiting or unlimited control work.

Unsupported inputs abort TCP in this reduced example; full protocol-error Close responses are not implemented. Do not deploy this parser as an internet-facing WebSocket client.

Test boundaries and rejection paths

No manual fixture is needed for the automated checks:

ctest --preset native-debug -R network.ws_lengths --output-on-failure

The independent Python peer decodes masks and length fields without importing the fixture's codec. It requires canonical outgoing headers and exact patterned payloads at 0, 125, 126, 255, 256, 65,535 and 65,536 bytes. The last case exercises a real valid eight-byte field in both directions, not just rejection of marker 127.

Other checks split two- and eight-byte length fields, split bodies, combine frames in one write, retain a Ping received alongside Upgrade, and preserve binary/empty/125-byte Ping replies and controls crossing Close. Invalid cases include nonminimal encodings, the forbidden high bit, an excessive advertised size without a body or EOF, extended controls, unsupported flags/opcodes, truncation and trailing data.

Deadline checks keep the peer open or send slow progress during the body/Ping wait, then verify that the original budget still expires. These are loopback behavior checks, not packet-boundary guarantees, throughput measurements or full WebSocket conformance tests.

Verification scope

Verified on 23 October 2026 on a Raspberry Pi 4B running 64-bit Raspberry Pi OS (Debian 13), plus a Linux x86-64 host. All 423 course checks passed in Debug and Release on both machines; 45 exercise this lesson. Representative direct-build checks also passed on both. The Pi used isolated official OpenSSL development headers with its existing runtime, without a system package change. This verifies local socket behavior, not LAN throughput.

Troubleshooting

  • payload_bytes must be 0..65536: the second argument is a decimal byte count. Do not pass a message string or try a size above the sample's policy.
  • nonminimal payload length: fix the sender's encoding choice. Small numbers must not be padded into larger length formats.
  • payload exceeds 65536-byte policy: the peer advertised too much data. This check intentionally fails before receiving that body; increasing the timeout will not help.
  • control payload must be at most 125 bytes: do not use extended formats for Ping, Pong or Close.
  • TCP ended before a complete frame: a length field or declared payload was truncated. A partial frame is not a shorter message.
  • Deadline or refusal: use a freshly started ws_lengths.py on the same loopback port. Larger payloads still share one fixed session budget.

Check your understanding

  1. Does marker 126 mean the payload contains exactly 126 bytes?
  2. Why is marker 127 required for a 65,536-byte payload?
  3. Does the payload length include the client's masking key?
  4. When should you check the local size limit relative to conversion and allocation?
  5. Can a binary Ping payload now contain 126 bytes?
  6. Can a Ping frame be inserted inside one large frame's payload?
Answers

Marker 126 selects the following two-byte length field. 65,536 no longer fits in an unsigned 16-bit field, so eight bytes are required. The mask is not part of the payload length. Validate the unsigned decoded value before narrowing, adding sizes, allocating or waiting for the body. Controls remain at most 125 bytes. Ping can occur between frames, not inside a frame's payload.

Continue the course

Previous: Ping and Pong · Course overview

Next: Fragmented Messages — separate frame lengths from message lengths and process controls between fragments.

References: Frame format and canonical lengths, Masking, Control frame constraints.

Donate