mirror of
https://github.com/yhirose/cpp-httplib.git
synced 2026-10-19 11:19:36 +00:00
Bring the READMEs and the docs pages (en and ja) in line with the current header: - Fix the client sample that does not compile, the Transfer-Encoding statement for default headers, the verifier callback comment, the thread pool spawn rule, the sanitize_filename description, and the inverted Accept-Encoding sentence. - Describe recent behaviour: TLS errors behind Read/Write failures, Host validation, Connection: close for a body without length, content_reader rules, refused CONNECT, WebSocketClient proxies, CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT, the SSE event size limit, and the payload limit of the Stream API. - Complete the API references of WebSocket, WebSocketClient and the stream:: helpers, and the SSE reconnect rules. - Fix cookbook pages: keychain loading on every backend, received Close status, a multipart sample that trusted the client's file name, an echo sample that sent binary as text, SNI, pre-request handler scope, stop() with WebSocket handlers, and the thread pool notes. - Restore the mutex in the LLM app's Chapter 5 code.
2.1 KiB
2.1 KiB
title, order, status
| title | order | status |
|---|---|---|
| C13. 全体タイムアウトを設定する | 13 | draft |
C12. タイムアウトを設定するで紹介した3種類のタイムアウトは、どれも一部の待ち時間にしか効きません。読み取りと書き込みのタイムアウトは「1回のrecvやsend」に、接続タイムアウトは接続の確立に対するものです。リクエスト全体の所要時間に上限を設けたい場合は、set_max_timeout()を使います。
基本の使い方
httplib::Client cli("http://localhost:8080");
cli.set_max_timeout(5000); // 5秒(ミリ秒単位)
auto res = cli.Get("/slow-endpoint");
ミリ秒単位で指定します。リクエストを始めてからこの時間が過ぎると、レスポンスを待っている途中でも打ち切られます。ただし、接続や送信で待たされる時間まで短くなるわけではありません。そちらはset_connection_timeoutとset_write_timeoutで調整します。
std::chronoで指定する
こちらにも、std::chronoの期間を受け取るオーバーロードがあります。
using namespace std::chrono_literals;
cli.set_max_timeout(5s);
どう使い分けるか
set_read_timeoutは「データが来ない時間」のタイムアウトなので、少しずつデータが流れ続ける状況では発火しません。たとえば1秒ごとに1バイト届くようなエンドポイントは、set_read_timeoutをいくら短くしてもタイムアウトしません。
一方、set_max_timeoutは「経過時間」に対する上限なので、こうしたケースでも確実に止められます。外部APIを叩くときや、ユーザーを待たせすぎたくないときに重宝します。
cli.set_connection_timeout(3s);
cli.set_read_timeout(10s);
cli.set_max_timeout(30s); // 全体で30秒を超えたら中断
Note:
set_max_timeout()は通常のタイムアウトと併用できます。短期的な無反応はset_read_timeoutで、長時間の処理はset_max_timeoutで、という二段構えにするのが安全です。