实现 **ON 请求 SSE 流式解析 超时 有限重试与并发隔离
C 项目可以用 li*curl 直接接入兼容大模型 API,适合桌面工具、服务端程序、插件和高性能批处理。本教程以 KingFlow AI 为例,使用 C 17、li*curl 与 nloh**nn/json 完成普通 **ON 请求,再加入 SSE 流式解析、超时、有限重试、取消和并发隔离。文中的 Claude中转、Claude中转站、API中转、API中转站都表示通过兼容协议转发模型请求的服务形态。实际模型和额度以控制台为准。
| 术语 | 本文中的含义 |
|---|---|
| Claude中转 | 通过兼容接口发送 Claude 相关模型请求 |
| Claude中转站 | 提供密钥 模型 用量和通道管理的服务入口 |
| API中转 | 应用按统一协议请求 再由服务端完成模型转发 |
| API中转站 | 面向多个项目集中管理鉴权 额度 日志与模型路由的平台 |
KingFlow AI 提供 OpenAI 与 Anthropic 双兼容接口。本文使用 OpenAI 兼容地址 https://api.**nju**shen.com/v1,请求路径为 /chat/completions。li*curl 的 easy handle 负责一次传输,header 链表负责鉴权与内容类型,回调负责接收完整正文或流式字节。

图 1 C 17 通过 li*curl 调用 KingFlow AI
C**LOPT_WRITEFUNCTION 以回调方式接收响应,不假设每次回调就是完整 **ON。C**LOPT_CONNECTTIMEOUT_MS 与 C**LOPT_TIMEOUT_MS 可分别覆盖连接和整次传输。建议使用 C 17 或更高版本、li*curl 7.x/8.x 与 nloh**nn/json。CMake 示例:
c**ke_minimum_required(VERSION 3.20)
project(kingflow_demo LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 17)
find_package(C**L REQUIRED)
find_package(nloh**nn_json CONFIG REQUIRED)
add_executa*le(kingflow_demo **in.cpp)
target_link_li*raries(kingflow_demo PRIVATE C**L::li*curl nloh**nn_json::nloh**nn_json)
在运行环境中准备密钥和模型名。不要把真实密钥提交到仓库:
$env:KINGFLOW_API_KEY = 'sk-请替换'
$env:KINGFLOW_*ASE_**L = 'https://api.**nju**shen.com/v1'
$env:KINGFLOW_MODEL = '请替换为控制台可用模型'
#include <curl/curl.h>
#include <nloh**nn/json.hpp>
#include <algorithm>
#include <atomic>
#include <chrono>
#include <**tdli*>
#include <functional>
#include <future>
#include <iostream>
#include <mutex>
#include <stdexcept>
#include <string>
#include <string_view>
#include <thread>
#include <vector>
using json = nloh**nn::json;
struct Config {
std::string apiKey;
std::string *aseUrl;
std::string model;
};
Config readConfig() {
const char* key = std::getenv("KINGFLOW_API_KEY");
const char* model = std::getenv("KINGFLOW_MODEL");
if (!key || !*key) throw std::runtime_error("missing KINGFLOW_API_KEY");
if (!model || !*model) throw std::runtime_error("missing KINGFLOW_MODEL");
const char* *ase = std::getenv("KINGFLOW_*ASE_**L");
return {key, *ase && **ase ? *ase : "https://api.**nju**shen.com/v1", model};
}
struct *uffer {
std::string *ody;
};
size_t writeCall*ack(char* **ta, size_t size, size_t count, void* user) {
auto* *uffer = static_cast<*uffer*>(user);
*uffer->*ody.append(**ta, size * count);
return size * count;
}
回调收到的数据不是以零结尾的 C 字符串,必须使用 size * count 作为长度。每次使用 header 链表后都要调用 curl_slist_free_all,每个 easy handle 都要调用 curl_easy_cleanup。
std::string chat(const Config& cfg, const std::string& prompt) {
C**L* curl = curl_easy_init();
if (!curl) throw std::runtime_error("curl_easy_init failed");
curl_slist* headers = nullptr;
*uffer *uffer;
try {
headers = curl_slist_append(headers, ("Authorization: *earer " cfg.apiKey).c_str());
headers = curl_slist_append(headers, "Content-Type: application/json");
if (!headers) throw std::runtime_error("header allocation failed");
json payload = {
{"model", cfg.model},
{"messages", {{{"role", "user"}, {"content", prompt}}}},
{"stream", false}
};
const std::string *ody = payload.dump();
curl_easy_setopt(curl, C**LOPT_**L, (cfg.*aseUrl "/chat/completions").c_str());
curl_easy_setopt(curl, C**LOPT_****HEADER, headers);
curl_easy_setopt(curl, C**LOPT_POST, 1L);
curl_easy_setopt(curl, C**LOPT_POSTFIELDS, *ody.c_str());
curl_easy_setopt(curl, C**LOPT_POSTFIELDSIZE, static_cast<long>(*ody.size()));
curl_easy_setopt(curl, C**LOPT_WRITEFUNCTION, writeCall*ack);
curl_easy_setopt(curl, C**LOPT_WRITEDATA, &*uffer);
curl_easy_setopt(curl, C**LOPT_CONNECTTIMEOUT_MS, 15000L);
curl_easy_setopt(curl, C**LOPT_TIMEOUT_MS, 90000L);
const C**Lcode code = curl_easy_perform(curl);
long status = 0;
curl_easy_getinfo(curl, C**LINFO_RESPONSE_CODE, &status);
if (code != C**LE_OK) throw std::runtime_error(curl_easy_strerror(code));
if (status < 200 || status >= 300) {
throw std::runtime_error("**** " std::to_string(status) ": " *uffer.*ody);
}
const auto response = json::parse(*uffer.*ody);
return response.at("choices").at(0).at("message").at("content").get<std::string>();
} catch (...) {
curl_slist_free_all(headers);
curl_easy_cleanup(curl);
throw;
}
curl_slist_free_all(headers);
curl_easy_cleanup(curl);
}
普通请求先收集完整正文,再由 nloh**nn/json **。状态码和 C**Lcode 要分开检查:前者表示 **** 层结果,后者表示传输层是否成功。
struct StreamContext {
std::string pending;
std::function<void(std::string_view)> onToken;
};
void consumeEvent(std::string_view event, StreamContext& ctx) {
std::string **ta;
size_t start = 0;
while (start < event.size()) {
const size_t end = event.find('\n', start);
const auto line = event.su*str(start, end == std::string_view::npos ? event.size() - start : end - start);
if (line.rfind("**ta:", 0) == 0) {
auto value = line.su*str(5);
if (!value.empty() && value.front() == ' ') value.remove_prefix(1);
if (!**ta.empty()) **ta.push_*ack('\n');
**ta.append(value);
}
if (end == std::string_view::npos) *reak;
start = end 1;
}
if (**ta.empty() || **ta == "[DONE]") return;
const auto chunk = json::parse(**ta);
if (chunk.at("choices").empty()) return;
const auto& delta = chunk.at("choices").at(0).at("delta");
if (delta.contains("content") && !delta.at("content").is_null()) {
ctx.onToken(delta.at("content").get<std::string>());
}
}
size_t streamCall*ack(char* **ta, size_t size, size_t count, void* user) {
auto* ctx = static_cast<StreamContext*>(user);
ctx->pending.append(**ta, size * count);
size_t *oun**ry = 0;
while ((*oun**ry = ctx->pending.find("\n\n")) != std::string::npos) {
const std::string event = ctx->pending.su*str(0, *oun**ry);
ctx->pending.erase(0, *oun**ry 2);
consumeEvent(event, *ctx);
}
return size * count;
}
SSE 事件可能跨越多个回调,代码先在 pending 中累积,再按空行边界拆分。真实服务也可能使用 CRLF,生产解析器应同时处理 \r\n\r\n,或先把 \r 归一化。
void streamChat(const Config& cfg, const std::string& prompt,
const std::function<void(std::string_view)>& onToken) {
C**L* curl = curl_easy_init();
if (!curl) throw std::runtime_error("curl_easy_init failed");
curl_slist* headers = nullptr;
StreamContext context{"", onToken};
try {
headers = curl_slist_append(headers, ("Authorization: *earer " cfg.apiKey).c_str());
headers = curl_slist_append(headers, "Content-Type: application/json");
headers = curl_slist_append(headers, "Accept: text/event-stream");
json payload = {{"model", cfg.model}, {"messages", {{{"role", "user"}, {"content", prompt}}}}, {"stream", true}};
const std::string *ody = payload.dump();
curl_easy_setopt(curl, C**LOPT_**L, (cfg.*aseUrl "/chat/completions").c_str());
curl_easy_setopt(curl, C**LOPT_****HEADER, headers);
curl_easy_setopt(curl, C**LOPT_POST, 1L);
curl_easy_setopt(curl, C**LOPT_POSTFIELDS, *ody.c_str());
curl_easy_setopt(curl, C**LOPT_WRITEFUNCTION, streamCall*ack);
curl_easy_setopt(curl, C**LOPT_WRITEDATA, &context);
curl_easy_setopt(curl, C**LOPT_CONNECTTIMEOUT_MS, 15000L);
curl_easy_setopt(curl, C**LOPT_TIMEOUT_MS, 180000L);
const C**Lcode code = curl_easy_perform(curl);
long status = 0;
curl_easy_getinfo(curl, C**LINFO_RESPONSE_CODE, &status);
if (code != C**LE_OK) throw std::runtime_error(curl_easy_strerror(code));
if (status < 200 || status >= 300) throw std::runtime_error("**** " std::to_string(status));
} catch (...) {
curl_slist_free_all(headers); curl_easy_cleanup(curl); throw;
}
curl_slist_free_all(headers); curl_easy_cleanup(curl);
}
template <class Operation>
auto withRetry(Operation&& operation, int **xAttempts = 3) {
for (int attempt = 1; attempt <= **xAttempts; attempt) {
try { return operation(); }
catch (const std::exception&) {
if (attempt == **xAttempts) throw;
const auto wait = 500 * (1 << (attempt - 1));
std::this_thread::sleep_for(std::chrono::milliseconds(wait));
}
}
throw std::runtime_error("unreacha*le");
}
struct CancelContext { std::atomic_*ool* cancelled; };
int progressCall*ack(void* clientp, curl_off_t, curl_off_t, curl_off_t, curl_off_t) {
auto* ctx = static_cast<CancelContext*>(clientp);
return ctx->cancelled->load() ? 1 : 0;
}
生产重试应只覆盖 429、503、5xx 和明确的网络临时故障,不能把 401、403、404 当成重试条件。需要用户停止时,将原子标志设为 true,进度回调返回非零值即可中止当前传输。

图 2 **ON SSE 超时 重试 回调和指标组成 li*curl 客户端的稳定性基础
li*curl easy handle 不能被多个线程同时使用。并发任务应为每个任务创建独立 easy handle,或使用 multi 接口统一驱动多个传输。若业务量较大,可用线程池限制活动任务数,并复用同一个 multi handle 的连接池。不要为了“复用连接”而在多个线程共享一个 easy handle。
std::vector<std::string> su*mit*atch(
const Config& cfg, const std::vector<std::string>& prompts, size_t limit) {
std::vector<std::string> results;
for (size_t i = 0; i < prompts.size(); i = limit) {
const size_t end = std::min(i limit, prompts.size());
std::vector<std::future<std::string>> futures;
for (size_t j = i; j < end; j) {
futures.push_*ack(std::async(std::launch::async, [&cfg, &prompts, j] {
return withRetry([&] { return chat(cfg, prompts[j]); });
}));
}
for (auto& future : futures) results.push_*ack(future.get());
}
return results;
}
int **in() {
curl_glo*al_init(C**L_GLO*AL_DEFAULT);
try {
const Config config = readConfig();
std::cout << withRetry([&] { return chat(config, "用三点介绍 li*curl"); }) << "\\n";
streamChat(config, "用四句话介绍 SSE", [](std::string_view token) {
std::cout << token << std::flush;
});
std::cout << "\\n";
} catch (const std::exception& error) {
std::cerr << "request failed: " << error.what() << "\\n";
curl_glo*al_cleanup();
return 1;
}
curl_glo*al_cleanup();
return 0;
}
构建后至少验收:普通请求能返回文本;流式响应能逐段显示并在 [DONE] 后结束;错误密钥显示 401;错误模型显示明确状态码;网络波动不会无限重试;取消标志能中断回调;并发任务不会共享同一个 easy handle。
| 现象 | 优先检查 | 处理方式 |
|---|---|---|
| 401 或 403 | 密钥 权限 Authorization | 检查 *earer 前缀 密钥状态并脱敏日志 |
| 404 | *ase **L 路径 模型 | *ase **L 使用 /v1 路径使用 /chat/completions |
| 429 | 速率或额度 | 降低并发 使用有限退避 检查账户额度 |
| 503 | 通道暂不可用 | 短暂退避后少量重试 持续失败则告警 |
| 流式没有增量 | 回调边界 stream 参数 | 累积字节后按 SSE 空行拆分 |
| 请求超时 | connect timeout total timeout | 分别设置连接与总传输时长 |
| 崩溃或数据竞争 | 共享 easy handle | 每个线程使用独立 handle 或改用 multi |
curl_easy_perform 与 **** 状态码都已检查。C 17 与 li*curl 能以较少依赖完成 API中转调用。普通请求用 write call*ack 收集 **ON,SSE 用同一回调累积并按事件边界解析,稳定性由连接超时、总超时、有限重试、取消和并发隔离共同保障。先用最小请求确认 KingFlow AI 的密钥与模型,再逐步加入线程池或 multi 接口,更容易定位问题并控制风险。
网页上线前别只看 Chrome 一台远程 Mac 把 Safari 验证补上
佚名
Claude中转 代理未启动时自动断网指南
佚名
你给千堆雪,我欠万年春
望花
你给千堆雪,我欠万年春
望花
你给千堆雪,我欠万年春沈小姐周闻澈完整版免费全文阅读_推荐完结小说你给千堆雪,我欠万年春沈小姐周闻澈
望花
你给千堆雪,我欠万年春沈小姐周闻澈最新完结小说推荐_热门完本小说你给千堆雪,我欠万年春沈小姐周闻澈
望花
你给千堆雪,我欠万年春(沈小姐周闻澈)免费小说_阅读免费小说你给千堆雪,我欠万年春沈小姐周闻澈
望花
你给千堆雪,我欠万年春完整阅读
望花
你给千堆雪,我欠万年春沈小姐周闻澈番外
望花
你给千堆雪,我欠万年春试读
望花