Files
cpp-httplib/docs-src/pages/en/cookbook/w02-websocket-ping.md
yhirose 254e576b50 Add Server::CustomRoute() for HTTP methods outside the built-in set (#2553)
* Add Server::CustomRoute() for HTTP methods outside the built-in set

parse_request_line validates the request method against a fixed whitelist and
rejects anything else with 400 before routing runs. That blocks WebDAV, where
PROPFIND, PROPPATCH, MKCOL, COPY, MOVE, LOCK and UNLOCK are ordinary methods
defined by RFC 4918, and it blocks extension methods such as UPnP's SUBSCRIBE.
The need has been open since #847.

Registering a handler is now what makes the server accept a method:

    svr.CustomRoute("PROPFIND", "/dav/:id", handler);

Because custom methods go through the normal dispatch path, patterns work the
way they do for Get() and friends, and the request body is available in
req.body. Serving these methods through set_pre_routing_handler was never
enough: the body has not been read at that point, so PROPPATCH and LOCK, which
require one, could not be implemented at all.

A HandlerWithContentReader overload is available too. The content reader gate
in routing() also fires when a custom method carries no body, matching what
expect_content() does unconditionally for POST/PUT/PATCH/DELETE, so a body-less
PROPFIND (RFC 4918 treats one as allprop) reaches its handler instead of
falling through to 404.

Method names are validated as RFC 9110 tokens, and the ten built-in methods are
refused. Seven of them are dispatched by the if/else chain in routing() before
the custom tables are consulted, so a route registered for one could never
fire; CONNECT, TRACE and PRI carry protocol-level meaning this library does not
route. A refused registration makes is_valid() return false, so listen() fails
rather than starting a server holding a handler that would never run. This is
also why SSLServer::is_valid() now chains to Server::is_valid() instead of only
checking ctx_.

Servers that never call CustomRoute() keep the previous per-request cost: the
built-in method set is checked first and short-circuits, and the custom lookup
returns early on an empty map.

* Add cookbook recipe for custom HTTP methods

The CustomRoute() docs were a section inside S01, which pushed that page to 90
lines, the longest in the cookbook, and mixed a separate feature into a page
about registering GET/POST/PUT/DELETE handlers. Move the section into its own
recipe and give it room for the part that was missing: the OPTIONS handler
returning DAV: and Allow, which WebDAV clients probe for before anything else.
S01 goes back to 68 lines and keeps a pointer to the new page.

The recipe is titled after the API rather than after WebDAV, and says outright
that generating the 207 Multi-Status XML, interpreting Depth and managing locks
are the reader's job. Routing the method is all the library does.

S23 takes order 42, so the TLS, SSE and WebSocket recipes shift to 43-57. That
only moves the sort key. Filenames, the T01/E01/W01 labels, the published URLs
and every cross-reference are untouched.
2026-08-25 19:31:42 -04:00

3.4 KiB
Raw Blame History

title, order, status
title order status
W02. Set a WebSocket Heartbeat 53 draft

WebSocket connections stay open for a long time, and proxies or load balancers will sometimes drop them for being "idle." To prevent that, you periodically send Ping frames to keep the connection alive. cpp-httplib can do this for you automatically.

Server side

svr.set_websocket_ping_interval(30); // ping every 30 seconds

svr.WebSocket("/chat", [](const auto &req, auto &ws) {
  // ...
});

Just pass the interval in seconds. Every WebSocket connection this server accepts will be pinged on that interval.

There's a std::chrono overload too.

using namespace std::chrono_literals;
svr.set_websocket_ping_interval(30s);

Client side

The client has the same API.

httplib::ws::WebSocketClient cli("ws://localhost:8080/chat");
cli.set_websocket_ping_interval(30);
cli.connect();

Call it before connect().

The default

The default interval is set by the build-time macro CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND. Usually you won't need to change it, but adjust downward if you're dealing with an aggressive proxy.

What about Pong?

The WebSocket protocol requires that Ping frames are answered with Pong frames. cpp-httplib responds to Pings automatically — you don't need to think about it in application code.

Picking an interval

Environment Suggested
Normal internet 3060s
Strict proxies (e.g. AWS ALB) 1530s
Mobile networks 60s+ (too short drains battery)

Too short wastes bandwidth; too long and connections get dropped. As a rule of thumb, target about half the idle timeout of whatever's between you and the client.

Warning: A very short ping interval spawns background work per connection and increases CPU usage. For servers with many connections, keep the interval modest.

Detecting an unresponsive peer

Sending pings alone doesn't tell you anything if the peer just silently dies — the TCP socket might still look open while the process on the other end is long gone. To catch that, enable the max-missed-pongs check: if N consecutive pings go unanswered, the connection is closed.

cli.set_websocket_max_missed_pongs(2); // close after 2 consecutive unacked pings

The server side has the same set_websocket_max_missed_pongs().

With a 30-second ping interval and max_missed_pongs = 2, a dead peer is detected within roughly 60 seconds and the connection is closed with CloseStatus::GoingAway and the reason "pong timeout".

The counter is reset whenever read() consumes an incoming Pong frame, so this only works if your code is actively calling read() in a loop — which is what a normal WebSocket client does anyway.

Why the default is 0

max_missed_pongs defaults to 0, which means "never close the connection because of missing pongs." Pings are still sent on the heartbeat interval, but their responses aren't checked. If you want unresponsive-peer detection, set it explicitly to 1 or higher.

Even with 0, a dead connection won't linger forever: while your code is inside read(), CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND (default 300 seconds = 5 minutes) acts as a backstop and read() fails if no frame arrives in time. Think of max_missed_pongs as the knob for detecting an unresponsive peer faster than that.

For handling a closed connection, see W03. Handle connection close.