mirror of
https://github.com/yhirose/cpp-httplib.git
synced 2026-11-27 20:58:28 +00:00
* 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>
100 lines
3.7 KiB
Markdown
100 lines
3.7 KiB
Markdown
---
|
|
title: "W03. 接続クローズをハンドリングする"
|
|
order: 54
|
|
status: "draft"
|
|
---
|
|
|
|
WebSocket接続は、クライアントかサーバーのどちらかが明示的に閉じるか、ネットワーク障害で切れると終了します。クローズ処理をきちんと書いておくと、リソースの後始末や再接続ロジックがきれいに書けます。
|
|
|
|
## クローズ状態の検出
|
|
|
|
`ws.read()`が`ReadResult::Fail`を返したら、接続が切れたか何らかのエラーが起きたということです。ループを抜けてハンドラから戻れば、そのWebSocket接続の処理は終わります。
|
|
|
|
```cpp
|
|
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_user_session(req);
|
|
});
|
|
```
|
|
|
|
`ws.is_open()`でも接続状態を確認できます。内部的には同じことを見ています。
|
|
|
|
## サーバー側から閉じる
|
|
|
|
サーバー側から明示的にクローズしたいときは、`close()`を呼びます。
|
|
|
|
```cpp
|
|
ws.close(httplib::ws::CloseStatus::Normal, "bye");
|
|
```
|
|
|
|
第1引数にクローズステータス、第2引数に理由(任意)を渡します。クローズステータスは`CloseStatus`列挙値で、代表的なものはこちらです。
|
|
|
|
| 値 | 意味 |
|
|
| --- | --- |
|
|
| `Normal` (1000) | 通常終了 |
|
|
| `GoingAway` (1001) | サーバーが終了するため |
|
|
| `ProtocolError` (1002) | プロトコル違反を検知 |
|
|
| `UnsupportedData` (1003) | 対応していないデータを受信 |
|
|
| `PolicyViolation` (1008) | ポリシー違反 |
|
|
| `MessageTooBig` (1009) | メッセージが大きすぎる |
|
|
| `InternalError` (1011) | サーバー内部エラー |
|
|
|
|
## クライアント側から閉じる
|
|
|
|
クライアント側でも同じAPIが使えます。
|
|
|
|
```cpp
|
|
cli.close(httplib::ws::CloseStatus::Normal);
|
|
```
|
|
|
|
`cli`を破棄したときにも自動的にクローズされますが、明示的に`close()`を呼んだほうが意図が伝わりやすいです。
|
|
|
|
## グレースフルシャットダウン
|
|
|
|
サーバーを停止するときに接続中のクライアントに「これから止まります」と伝えたい場合は、`GoingAway`を使います。
|
|
|
|
```cpp
|
|
ws.close(httplib::ws::CloseStatus::GoingAway, "server restarting");
|
|
```
|
|
|
|
`read()`が`Fail`を返したあとは、`close_status()`と`close_reason()`で切断の理由を取り出せます。相手のCloseフレームのステータスと理由、ステータスがなければ`NoStatus` (1005)、Closeフレームなしで切れた場合は`Abnormal` (1006)です。サーバー側でもクライアント側でも同じです。
|
|
|
|
```cpp
|
|
std::string msg;
|
|
while (cli.read(msg)) {}
|
|
if (cli.close_status() == httplib::ws::CloseStatus::GoingAway) {
|
|
// サーバーが再起動中: あとで再接続する
|
|
}
|
|
```
|
|
|
|
## サンプル: 簡単なチャット終了
|
|
|
|
```cpp
|
|
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:** ネットワーク障害で突然切断された場合、`close()`を呼ぶ暇もなく`read()`が`Fail`を返します。後始末はハンドラ終了時にまとめて行うようにしておくと、どちらのパターンでも対応できます。
|