* Add set_websocket_max_message_length() to Server and WebSocketClient The largest WebSocket frame and message read() accepts was fixed at compile time by CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, so a program running several servers, or one build of httplib.h shared by many applications, could not pick a limit per server. Checking the size after read() does not help, since by then the message has already been assembled in memory. Add set_websocket_max_message_length() to Server and WebSocketClient, next to the heartbeat setters. It defaults to the macro, is handed to ws::WebSocket like the ping settings, and replaces the macro in both checks in read(): the declared frame length and the size of a message assembled from fragments. 0 still means no limit, and a message over the limit still makes read() fail and close the connection. On the client, the value applies from the next connect(). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Keep control frames out of the message limit and trim the limit tests With a limit under 125 bytes, a frame read between messages was held to the limit itself, so a Ping or a Close with a reason was answered with 1009. The frame limit is now what is left of the message limit, but never less than 125, so control frames always fit; a small data frame over the limit is still refused by the message check. The test that sent two 16 MiB messages is replaced by cheap checks in the remaining tests: a header that announces more than the limit is refused before its payload, a Ping over the limit is answered, and 0 lifts the limit on the client. * Fold the server limit tests and drop unused constructor defaults The two server-side tests become one on an echo server, checked with raw_websocket_reply(): a Ping over the limit is answered, a message at the limit is echoed, one over it gets 1009, and so does a header that announces more than the limit. Every caller of the WebSocket constructors passes the settings, so their defaults are dropped. --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: yhirose <yuji.hirose.bug@gmail.com>
4.0 KiB
title, order, status
| title | order | status |
|---|---|---|
| W04. バイナリフレームを送受信する | 55 | draft |
WebSocketにはテキストフレームとバイナリフレームの2種類があります。JSONやプレーンテキストならテキスト、画像や独自プロトコルの生データならバイナリ、という使い分けです。cpp-httplibのsend()は、オーバーロードで両者を自動的に切り替えます。
送り分けの仕組み
ws.send(std::string("Hello")); // テキスト
ws.send("Hello", 5); // バイナリ
ws.send(binary_data, binary_data_size); // バイナリ
std::stringを受け取るオーバーロードはテキスト、const char*とサイズを受け取るオーバーロードはバイナリです。ちょっと紛らわしいですが、覚えてしまえば直感的です。
文字列をバイナリとして送りたい場合は、.data()と.size()を明示的に渡します。
std::string raw = build_binary_payload();
ws.send(raw.data(), raw.size()); // バイナリフレーム
受信時の判別
ws.read()の返り値で、受信したフレームがテキストかバイナリかを判別できます。
std::string msg;
auto result = ws.read(msg);
switch (result) {
case httplib::ws::ReadResult::Text:
std::cout << "text: " << msg << std::endl;
break;
case httplib::ws::ReadResult::Binary:
std::cout << "binary: " << msg.size() << " bytes" << std::endl;
handle_binary(msg.data(), msg.size());
break;
case httplib::ws::ReadResult::Fail:
// エラーまたは切断
break;
case httplib::ws::ReadResult::Timeout:
// 読み取りタイムアウト。接続は開いたまま
break;
}
バイナリフレームもstd::stringに入って渡されますが、中身はバイト列なので注意してください。msg.data()とmsg.size()で生のバイトとして扱えます。
バイナリを使うべき場面
- 画像・動画・音声: Base64でエンコードせずにそのまま送れるので、オーバーヘッドがない
- 独自プロトコル: protobufやMessagePackなどの構造化バイナリフォーマット
- ゲームのネットワーク通信: 低レイテンシが求められる場合
- センサーデータのストリーミング: 数値列をそのまま送る
Pingもバイナリフレームの一種
WebSocketのPing/PongフレームもOpcodeレベルではバイナリに近い扱いですが、cpp-httplibが自動で処理するので、アプリケーションコードで意識する必要はありません。W02. ハートビートを設定するを参照してください。
サンプル: 画像を送る
// サーバー側: 画像を送りつける
svr.WebSocket("/image", [](const auto &req, auto &ws) {
auto img = read_image_file("logo.png");
ws.send(img.data(), img.size());
});
// クライアント側: 受け取ってファイルに保存
httplib::ws::WebSocketClient cli("ws://localhost:8080/image");
cli.connect();
std::string buf;
if (cli.read(buf) == httplib::ws::ReadResult::Binary) {
std::ofstream ofs("received.png", std::ios::binary);
ofs.write(buf.data(), buf.size());
}
テキストとバイナリを混ぜて送ることもできます。たとえば「制御メッセージはJSON、データ本体はバイナリ」といったプロトコルを組み立てると、メタデータと生データを効率よく扱えます。
Note: 受信できるメッセージの大きさは
CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH(デフォルトは16MB、0なら無制限)、またはServerやWebSocketClientのset_websocket_max_message_length()で設定した値までです。これを超えるとread()はFailを返し、接続は終了します。上限以内でもメッセージはまるごとメモリに載るので、巨大なデータを送るときは、アプリケーション側で分割して送るのが安全です。