mirror of
https://github.com/yhirose/cpp-httplib.git
synced 2026-09-02 14:53:46 +00:00
* 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.
89 lines
3.5 KiB
Markdown
89 lines
3.5 KiB
Markdown
---
|
||
title: "W01. WebSocketエコーサーバー/クライアントを実装する"
|
||
order: 52
|
||
status: "draft"
|
||
---
|
||
|
||
WebSocketは、クライアントとサーバーの間で**双方向**にメッセージをやり取りするためのプロトコルです。cpp-httplibはサーバーとクライアントの両方のAPIを提供しています。まずは一番シンプルなエコーサーバーから見てみましょう。
|
||
|
||
## サーバー: エコーサーバー
|
||
|
||
```cpp
|
||
#include <httplib.h>
|
||
|
||
int main() {
|
||
httplib::Server svr;
|
||
|
||
svr.WebSocket("/echo", [](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) {
|
||
break;
|
||
}
|
||
ws.send(msg); // 受け取った内容をそのまま返す
|
||
}
|
||
});
|
||
|
||
svr.listen("0.0.0.0", 8080);
|
||
}
|
||
```
|
||
|
||
`svr.WebSocket()`でWebSocket用のハンドラを登録します。ハンドラが呼ばれた時点で、すでにWebSocketのハンドシェイクは完了しています。ループの中で`ws.read()`して`ws.send()`するだけで、エコー動作が完成します。
|
||
|
||
`read()`の返り値は`ReadResult`列挙値で、次の3種類です。
|
||
|
||
- `ReadResult::Text`: テキストメッセージを受信
|
||
- `ReadResult::Binary`: バイナリメッセージを受信
|
||
- `ReadResult::Fail`: エラー、または接続が閉じた
|
||
|
||
## クライアント: エコーを叩く
|
||
|
||
```cpp
|
||
#include <httplib.h>
|
||
|
||
int main() {
|
||
httplib::ws::WebSocketClient cli("ws://localhost:8080/echo");
|
||
if (!cli.connect()) {
|
||
std::cerr << "failed to connect" << std::endl;
|
||
return 1;
|
||
}
|
||
|
||
cli.send("Hello, WebSocket!");
|
||
|
||
std::string msg;
|
||
if (cli.read(msg) != httplib::ws::ReadResult::Fail) {
|
||
std::cout << "received: " << msg << std::endl;
|
||
}
|
||
|
||
cli.close();
|
||
}
|
||
```
|
||
|
||
URLには`ws://`(平文)または`wss://`(TLS)を指定します。`connect()`でハンドシェイクを行い、あとは`send()`と`read()`でサーバーと同じAPIでやり取りできます。
|
||
|
||
## テキストとバイナリの送り分け
|
||
|
||
`send()`には2つのオーバーロードがあり、テキストとバイナリで使い分けられます。
|
||
|
||
```cpp
|
||
ws.send("Hello"); // テキストフレーム
|
||
ws.send(binary_data, binary_data_size); // バイナリフレーム
|
||
```
|
||
|
||
`std::string`を受け取るオーバーロードはテキスト、`const char*`とサイズを受け取るオーバーロードはバイナリとして送られます。詳しくは[W04. バイナリフレームを送受信する](../w04-websocket-binary)を参照してください。
|
||
|
||
## スレッドとの関係
|
||
|
||
WebSocket接続はハンドラが終わるまで生き続けるので、1接続につきワーカースレッドを1つ占有します。同時接続数が多い場合は、スレッドプールを動的スケーリングに設定しましょう。
|
||
|
||
```cpp
|
||
svr.new_task_queue = [] {
|
||
return new httplib::ThreadPool(8, 128);
|
||
};
|
||
```
|
||
|
||
詳細は[S21. マルチスレッド数を設定する](../s21-thread-pool)を参照してください。
|
||
|
||
> **Note:** HTTPSサーバーの上でWebSocketを動かしたいときは、`httplib::Server`の代わりに`httplib::SSLServer`を使えば、同じ`WebSocket()`ハンドラがそのまま動きます。クライアント側は`wss://`スキームを指定するだけです。CA証明書やクライアント証明書の設定は[W05. wss接続でTLSを設定する](../w05-websocket-tls)を参照してください。
|