* Expose the WebSocket close status and reason When the peer closed a WebSocket, read() returned Fail and the code and reason of its Close frame were dropped after the reply, so a handler or a WebSocketClient user could not tell a normal close from going away, an application code, or a connection that ended without a Close at all. Add close_status() and close_reason() to ws::WebSocket and WebSocketClient. Once read() has returned Fail they report the code and reason of the peer's Close (RFC 6455 7.1.5 and 7.1.6), NoStatus (1005) when it carried no code, ProtocolError when it was malformed, and Abnormal (1006) when none came. After a close() of our own they report the peer's reply. Application codes (3000-4999) come back as a CloseStatus too, as close() already takes them. The status is set once, under the read mutex, with the reason written before it, so the accessors may be called from any thread. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Return close_reason() by value and fold the handler-side close tests WebSocketClient::close_reason() returned a reference into the connection that connect() replaces, so a reference kept across a reconnect dangled. Both close_reason() accessors now return a copy of the reason, which is at most 123 bytes. The six handler-side tests become one table-driven test on one server, and the client test checks the reason still reads after a reconnect. * Decode the close code in one place and fold the client close tests is_valid_close_payload() and set_close_status() each decoded the code by hand; they now share impl::close_code(). The client-side checks move into the existing CloseHandshake, CloseWithStatus and ClientCloseWithStatus tests, which already reach those states, and the reconnect check becomes a static_assert on close_reason()'s type. --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: yhirose <yuji.hirose.bug@gmail.com>
2.9 KiB
title, order, status
| title | order | status |
|---|---|---|
| W03. Handle Connection Close | 54 | draft |
A WebSocket ends when either side closes it explicitly, or when the network drops. Handle close cleanly, and your cleanup and reconnect logic stays tidy.
Detect a closed connection
When ws.read() returns ReadResult::Fail, the connection is gone — either cleanly or with an error. Break out of the loop and the handler will finish.
svr.WebSocket("/chat", [](const httplib::Request &req, httplib::ws::WebSocket &ws) {
std::string msg;
while (ws.is_open()) {
auto result = ws.read(msg);
if (result == httplib::ws::ReadResult::Fail) {
std::cout << "disconnected" << std::endl;
break;
}
handle_message(ws, msg);
}
// cleanup runs once we're out of the loop
cleanup_user_session(req);
});
You can also check ws.is_open() — it's the same signal from a different angle.
Close from the server side
To close explicitly, call close().
ws.close(httplib::ws::CloseStatus::Normal, "bye");
The first argument is the close status; the second is an optional reason. Common CloseStatus values:
| Value | Meaning |
|---|---|
Normal (1000) |
Normal closure |
GoingAway (1001) |
Server is shutting down |
ProtocolError (1002) |
Protocol violation detected |
UnsupportedData (1003) |
Received data that can't be handled |
PolicyViolation (1008) |
Violated a policy |
MessageTooBig (1009) |
Message too large |
InternalError (1011) |
Server-side error |
Close from the client side
The client API is identical.
cli.close(httplib::ws::CloseStatus::Normal);
Destroying the client also closes the connection, but calling close() explicitly makes the intent clearer.
Graceful shutdown
To notify in-flight clients that the server is going down, use GoingAway.
ws.close(httplib::ws::CloseStatus::GoingAway, "server restarting");
Once read() has returned Fail, close_status() and close_reason() tell you why: the status and reason of the peer's Close, NoStatus (1005) if it sent no status, or Abnormal (1006) if the connection ended without a Close. This works the same on the server and the client.
std::string msg;
while (cli.read(msg)) {}
if (cli.close_status() == httplib::ws::CloseStatus::GoingAway) {
// the server is restarting: reconnect later
}
Example: a tiny chat with quit
svr.WebSocket("/chat", [](const auto &req, auto &ws) {
std::string msg;
while (ws.is_open()) {
if (ws.read(msg) == httplib::ws::ReadResult::Fail) break;
if (msg == "/quit") {
ws.send("goodbye");
ws.close(httplib::ws::CloseStatus::Normal, "user quit");
break;
}
ws.send("echo: " + msg);
}
});
Note: On a sudden network drop,
read()returnsFailwith no chance to callclose(). Put your cleanup at the end of the handler, and both paths — clean close and abrupt disconnect — end up in the same place.