Module 6 · Lesson 33 of 108

WebSockets for server push

Add a WebSocket endpoint that pushes live telemetry, handles slow clients, and can be verified from a browser.

  • Beginner to advanced
  • 7 min read
  • 50 min lab
What you will need

Ubuntu 24.04 in WSL2 or a VM, a C++17 compiler, Boost.Beast and Boost.Asio headers, and Firefox or Chromium with developer tools

Your place in the module
By the end you can 4 objectives
  • Trace an HTTP/1.1 WebSocket upgrade from request to first telemetry message
  • Identify WebSocket data and control frames and explain ping/pong keepalive
  • Implement bounded server push with Boost.Beast
  • Verify unsolicited telemetry and connection cleanup with a browser client
Video coming soonWebSockets for server push
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from Designing a REST API and choosing a library
  • A latest-reading endpoint can return a cached sample with its original acquisition timestamp.
  • Idempotency describes the intended server effect of repeated requests.
  • An HTTP server library handles protocol mechanics while the application defines the resource contract.
01

Upgrade an HTTP connection

3 min read

REST is request and response; telemetry needs the server to speak first, so this lesson introduces the WebSocket upgrade and its frames.

Consider a device dashboard that shows the current temperature. The device can produce a reading while the browser has no HTTP request in progress. On Linux, TCP already gives both endpoints a reliable, ordered byte stream, as described in tcp(7). WebSocket defines how to start using that stream for messages and how each endpoint can identify where a message begins and ends.

The HTTP/1.1 handshake in RFC 6455 starts with a GET request to a path such as /telemetry. The browser includes Upgrade: websocket and Connection: Upgrade, which ask the server to switch protocols on this connection. It sends Sec-WebSocket-Version: 13 and a Sec-WebSocket-Key containing a freshly generated random value encoded in Base64. Your server first decides whether the request should reach the WebSocket handler. For the lab, accept an upgrade at /telemetry and keep ordinary HTTP requests in the HTTP handler.

On acceptance, the server replies with 101 Switching Protocols, the upgrade headers, and Sec-WebSocket-Accept. The server library derives the accept value by appending the protocol's fixed identifier to the key as sent, hashing the result with SHA-1, and encoding the digest in Base64. The browser checks the response before it reports that the connection is open. The accept value confirms that the server understood the handshake. It does not identify the user or the device.

The same TCP connection now carries WebSocket frames. Each new browser connection starts with its own handshake and maintains its own connection state. If a request receives an ordinary HTTP response instead of a valid 101, the browser cannot start a WebSocket session. If the browser shows a successful upgrade but receives no samples, look next at whether the server registered the session and started writing when a sample became available.

HTTP upgrade and telemetry pushBrowserDevice serviceGET /telemetry101 Switching ProtocolsText messageText message1. Browser → Device serviceGET /telemetry2. Device service → Browser101 Switching Protocols3. Device service → BrowserText message4. Device service → BrowserText message
The browser requests an upgrade once, then the device sends telemetry as samples become available.
02

Data frames and connection control

3 min read

A can carry application data or control information. A telemetry message may fit in one frame or span several. A TCP read may return bytes from part of a frame or from several frames at once. The WebSocket library parses the stream and puts fragmented messages back together so the application can work with complete messages.

A Text frame starts a UTF-8 text message. Send each JSON telemetry record as one text message so a browser can parse it directly. A Binary frame starts a message containing arbitrary bytes. A Continuation frame carries more of a fragmented text or binary message. The final-frame flag identifies the last frame of a message. Client-to-server frames must be masked, and server-to-client frames must be unmasked. The WebSocket library handles framing and masking.

Ping, Pong, and Close are control frames. They are never fragmented and can appear between the fragments of a data message. Either endpoint can send a Ping. An endpoint that receives one replies with a Pong carrying the same payload, unless it has already received a Close. The browser handles this exchange internally. Browser JavaScript receives application messages through message events and has no API to send protocol Ping frames or handle protocol Pong frames itself.

For keepalive, configure the service to send a Ping when a connection has been idle and to terminate sessions that exceed the idle timeout. This lets the application reclaim resources after failures where the peer vanishes without sending a Close. With Boost.Beast, the built-in timeout policy measures incoming activity. Automatic keepalive pings probe the connection during that idle period. A responsive browser can therefore keep an idle telemetry session open by returning Pong frames. A Pong shows that the peer's WebSocket endpoint responded. It does not show that JavaScript parsed or displayed the most recent sample. TCP SO_KEEPALIVE, described in socket(7), is a separate socket option.

Either endpoint can initiate an orderly shutdown by sending a Close frame. The recipient sends a Close in response if it has not already sent one. Stop scheduling telemetry when shutdown starts. If a transport error interrupts the exchange, remove the session and release its queued data anyway. A client that reconnects establishes a fresh session and can receive the latest available reading.

Ping, Pong and CloseBrowserDevice servicePingPongCloseClose reply1. Device service → BrowserPing2. Browser → Device servicePong3. Browser → Device serviceClose4. Device service → BrowserClose reply
An idle connection can exchange Ping and Pong, then close with a separate handshake.
03

Push live telemetry with Boost.Beast

4 min read

Use Boost.Beast with Boost.Asio for the WebSocket session. A practical lab structure is one listener bound to 127.0.0.1, one event loop running on one thread, and one WebSocket session per connected client. Use port 8080 if it is free. Serve a small page at / and accept WebSocket upgrades at /telemetry. Both routes can use the same listener. A periodic boost::asio::steady_timer can generate one synthetic sample per second, so the exercise runs without a sensor board.

When the HTTP handler reads a complete request, use boost::beast::websocket::is_upgrade(req) together with the request target to identify the telemetry route. For an accepted route, transfer the connection into a boost::beast::websocket::stream and call async_accept(req, handler) with the parsed request. Register the session for telemetry only after the accept handler reports success. Keep the session object alive while its asynchronous operations are outstanding. On acceptance failure, release the connection without adding it to the subscriber list.

For the asynchronous stream, configure boost::beast::websocket::stream_base::timeout with set_option. Set an idle_timeout and enable keep_alive_pings. Beast can send an automatic Ping after half the configured idle interval without incoming activity. After the upgrade, keep an async_read outstanding so Beast can process control frames and deliver timeout errors. When a read completes with an application message, consume that message from the receive buffer and start the next read. The lab protocol needs no commands from clients, so discard any received application message and use read_message_max to limit its size. A normal closure is reported as boost::beast::websocket::error::closed. Close or error cleanup should remove the session from the subscriber list once, even if more than one handler reports termination.

Give each sample a sequence number that increases for the life of the server process, and use a field name that identifies the unit, such as temperature_c. Generate and serialize the sample once per timer tick, then offer the same JSON message to each active session. Call text(true) for text messages and use async_write to send the complete message. Keep the memory referenced by the write buffer valid and unchanged until its completion handler runs.

The producer can generate a reading while a client write is pending. Start only one application write at a time per session. For a dashboard that displays current values, retain one additional sample per client while the write is active. When a new sample arrives, replace that pending sample. After a successful write, send the newest pending sample if one exists. The active write keeps its original buffer throughout. This policy bounds the number of samples in the application's outgoing queue for each client. If a sequence number is skipped on an otherwise open connection under this policy, the server may have discarded an older pending sample. TCP still delivers the bytes it carries in order.

Per-client telemetry writesNo active writeWritingWriting with pendingTransitionsSample arrivesNo active writeWritingWrite completesWritingNo active writeSample arrivesWritingWriting with pendingReplace pending sampleWriting with pendingWriting with pendingWrite pending sampleWriting with pendingWritingNo active writeWritingWriting with pendingTransitionsSample arrivesNo activewriteWritingWrite completesWritingNo activewriteSample arrivesWritingWritingwithpendingReplace pending sampleWritingwithpendingWritingwithpendingWrite pending sampleWritingwithpendingWriting
Each session keeps its active write and, when needed, one pending sample that can be replaced.

To observe the result, serve a page at http://127.0.0.1:8080/ and run this JavaScript from that page, or paste it into the developer console while the page is open. The browser initiates the upgrade when the socket is created. The message handler logs each sample, and the code sends no application messages to the service.

javascript
const telemetry = new WebSocket(`ws://${location.host}/telemetry`);
telemetry.addEventListener("message", (event) => {
  const sample = JSON.parse(event.data);
  console.log(sample.seq, sample.temperature_c);
});
telemetry.addEventListener("close", (event) => {
  console.log(event.code, event.wasClean);
});

In the browser's Network panel, inspect the /telemetry request and its 101 response. Check that the console receives several samples with increasing sequence numbers. A second browser tab creates a second subscription. If you connected through the console, call telemetry.close() there and check that the other tab continues to receive updates. This checks that the server tracks connections independently. The browser or server may buffer writes briefly, so a tab that appears slow does not by itself prove that the pending slot was replaced. For a repeatable test, add a deliberate delay before starting the next write in one session, and replace the pending sample during that delay.

The lab uses ws:// on loopback. TLS for the network app follows by showing how to protect network traffic and verify the peer when clients connect to the device over a network.

Key takeaways

  • A successful HTTP/1.1 upgrade switches the existing TCP connection to WebSocket framing.
  • Either endpoint can send messages after the upgrade, and a server can publish telemetry without a client message.
  • Ping and Pong test connection responsiveness, while Close starts or completes the closing handshake.
  • One pending latest sample per client bounds the application queue for current-value telemetry.
Reflect
  1. Explain to a colleague, in two sentences: trace an HTTP/1.1 WebSocket upgrade from request to first telemetry message
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. What surprised you when you ran the commands yourself?
On a real board

Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.

References and further reading

Find your next step

↑ ↓ to move · Enter to open · Esc to close