Explore Enterprise Education Gitee Premium Gitee AI AI teammates
Fetch the repository succeeded.
Open Source > Development Lib > Common Toolkit &&
Donate
Please sign in before you donate.
Scan WeChat QR to Pay
Cancel
Complete
Prompt
Switch to Alipay.
OK
Cancel
103 Star 575 Fork 242

cpp-master/cpp-tbox

Create your Gitee Account
Explore and code with more than 14 million developers,Free private repositories !:)
Sign up
Already have an account? Sign in
文件
develop
Branches (18)
Tags (32)
master
develop
opt/websocket
feat/http-client
feature/tls-crypto-https
fix/jsonrpc
feat/mqtt-reconnect
tidy/doc
wlabs-develop
fix/terminal-mem-leak
feat/use-config-enable-epoll
feature-Broker
opt-loop-wdog
feature-DBus
feature-epoll
feature-update-readme
feature-Dns
feature-TcpSSL
v1.15.5
v1.15.4
v1.14.4
v1.13.10
v1.13.2
v1.12.28
v1.12.25
v1.12.22
v1.12.20
v1.12.10
v1.12.0
v1.11.14
v1.11.12
v1.11.11
v1.11.5
v1.11.4
v1.11.2
v1.11.0
v1.10.27
v1.10.23
develop
Branches (18)
Tags (32)
master
develop
opt/websocket
feat/http-client
feature/tls-crypto-https
fix/jsonrpc
feat/mqtt-reconnect
tidy/doc
wlabs-develop
fix/terminal-mem-leak
feat/use-config-enable-epoll
feature-Broker
opt-loop-wdog
feature-DBus
feature-epoll
feature-update-readme
feature-Dns
feature-TcpSSL
v1.15.5
v1.15.4
v1.14.4
v1.13.10
v1.13.2
v1.12.28
v1.12.25
v1.12.22
v1.12.20
v1.12.10
v1.12.0
v1.11.14
v1.11.12
v1.11.11
v1.11.5
v1.11.4
v1.11.2
v1.11.0
v1.10.27
v1.10.23
Clone or Download
Clone/Download
Prompt
To download the code, please copy the following command and execute it in the terminal
To ensure that your submitted code identity is correctly recognized by Gitee, please execute the following command.
When using the SSH protocol for the first time to clone or push code, follow the prompts below to complete the SSH configuration.
1 Generate RSA keys.
2 Obtain the content of the RSA public key and configure it in SSH Public Keys
To use SVN on Gitee, please visit the usage guide
When using the HTTPS protocol, the command line will prompt for account and password verification as follows. For security reasons, Gitee recommends configure and use personal access tokens instead of login passwords for cloning, pushing, and other operations.
Username for 'https://gitee.com': userName
Password for 'https://userName@gitee.com': # Private Token
develop
Branches (18)
Tags (32)
master
develop
opt/websocket
feat/http-client
feature/tls-crypto-https
fix/jsonrpc
feat/mqtt-reconnect
tidy/doc
wlabs-develop
fix/terminal-mem-leak
feat/use-config-enable-epoll
feature-Broker
opt-loop-wdog
feature-DBus
feature-epoll
feature-update-readme
feature-Dns
feature-TcpSSL
v1.15.5
v1.15.4
v1.14.4
v1.13.10
v1.13.2
v1.12.28
v1.12.25
v1.12.22
v1.12.20
v1.12.10
v1.12.0
v1.11.14
v1.11.12
v1.11.11
v1.11.5
v1.11.4
v1.11.2
v1.11.0
v1.10.27
v1.10.23
cpp-tbox
/
modules
/
http
/
client
/
client_impl.cpp
cpp-tbox
/
modules
/
http
/
client
/
client_impl.cpp
client_impl.cpp 11.68 KB
Copy Edit Raw Blame History
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
/*
* .============.
* // M A K E / \
* // C++ DEV / \
* // E A S E / \/ \
* ++ ----------. \/\ .
* \\ \ \ /\ /
* \\ \ \ /
* \\ \ \ /
* -============'
*
* Copyright (c) 2026 Hevake and contributors, all rights reserved.
*
* This file is part of cpp-tbox (https://github.com/cpp-main/cpp-tbox)
* Use of this source code is governed by MIT license that can be found
* in the LICENSE file in the root of the source tree. All contributing
* project authors may be found in the CONTRIBUTORS.md file in the root
* of the source tree.
*/
#include "client_impl.h"
#include <tbox/base/log.h>
#include <tbox/base/assert.h>
#include <tbox/base/wrapped_recorder.h>
#include <tbox/event/timer_event.h>
#include <tbox/util/buffer.h>
namespace tbox {
namespace http {
namespace client {
using namespace std;
using namespace std::placeholders;
using namespace event;
using namespace network;
Client::Impl::Impl(Client *wp_parent, Loop *wp_loop)
: wp_parent_(wp_parent)
, wp_loop_(wp_loop)
, tcp_client_(wp_loop)
{ }
Client::Impl::~Impl()
{
TBOX_ASSERT(cb_level_ == 0);
cleanup();
}
bool Client::Impl::initialize(const SockAddr &server_addr)
{
if (state_ != State::kNone) {
LogWarn("state not right, can't initialize");
return false;
}
if (!tcp_client_.initialize(server_addr))
return false;
tcp_client_.setConnectedCallback(bind(&Impl::onTcpConnected, this));
tcp_client_.setDisconnectedCallback(bind(&Impl::onTcpDisconnected, this));
tcp_client_.setReceiveCallback(bind(&Impl::onTcpReceived, this, _1), 0);
state_ = State::kInited;
return true;
}
void Client::Impl::setTlsConfig(const TlsConfig &config)
{
tcp_client_.setTlsConfig(config);
}
bool Client::Impl::start()
{
if (state_ != State::kInited) {
LogWarn("state not right, can't start");
return false;
}
if (tcp_client_.start()) {
state_ = State::kConnecting;
return true;
}
return false;
}
void Client::Impl::stop()
{
if (state_ == State::kConnected || state_ == State::kConnecting || state_ == State::kReconnWaiting) {
tcp_client_.stop();
//! 清理所有缓存和待处理的请求
failAllPendingRequests(StatusCode::k503_ServiceUnavailable, "client stopped");
for (auto &item : cached_requests_)
CHECK_DELETE_RESET_OBJ(item.sp_req);
cached_requests_.clear();
res_parser_.reset();
state_ = State::kInited;
}
}
void Client::Impl::cleanup()
{
if (state_ != State::kNone) {
stop();
//! 释放所有超时定时器
for (auto &item : pending_requests_)
CHECK_DELETE_RESET_OBJ(item.sp_timer);
pending_requests_.clear();
//! 释放所有缓存请求
for (auto &item : cached_requests_)
CHECK_DELETE_RESET_OBJ(item.sp_req);
cached_requests_.clear();
tcp_client_.cleanup();
state_ = State::kNone;
}
}
void Client::Impl::request(const Request &req, const RespondCallback &cb)
{
if (state_ == State::kNone) {
LogWarn("state is kNone, need initialize first");
return;
}
sendRequest(req, cb);
}
void Client::Impl::request(Method method, const string &path, const RespondCallback &cb)
{
Request req;
req.method = method;
req.http_ver = HttpVer::k1_1;
req.url.path = path;
request(req, cb);
}
void Client::Impl::request(Method method, const string &path, const string &body,
const Headers &headers, const RespondCallback &cb)
{
Request req;
req.method = method;
req.http_ver = HttpVer::k1_1;
req.url.path = path;
req.body = body;
req.headers = headers;
request(req, cb);
}
void Client::Impl::setAutoReconnect(bool enable)
{
auto_reconnect_ = enable;
tcp_client_.setAutoReconnect(enable);
}
void Client::Impl::setReconnectDelayCalcFunc(const ReconnectDelayCalc &func)
{
tcp_client_.setReconnectDelayCalcFunc(func);
}
void Client::Impl::setRequestTimeout(chrono::milliseconds ms)
{
request_timeout_ms_ = ms;
}
void Client::Impl::setContextLogEnable(bool enable)
{
context_log_enable_ = enable;
}
void Client::Impl::setConnectedCallback(const ConnectedCallback &cb)
{
connected_cb_ = cb;
}
void Client::Impl::setConnectFailCallback(const ConnectFailCallback &cb)
{
connect_fail_cb_ = cb;
}
void Client::Impl::setDisconnectedCallback(const DisconnectedCallback &cb)
{
disconnected_cb_ = cb;
}
//! ============ TCP 连接回调 ============
void Client::Impl::onTcpConnected()
{
RECORD_SCOPE();
state_ = State::kConnected;
LogDbg("connected");
//! 发送缓存中的请求
sendCachedRequests();
if (connected_cb_) {
++cb_level_;
connected_cb_();
--cb_level_;
}
}
void Client::Impl::onTcpConnectFail()
{
RECORD_SCOPE();
LogDbg("connect fail");
//! failAllPendingRequests 中会处理所有 pending 请求
//! 但 connect fail 时,pending_requests_ 应为空(因为未连接时请求在 cached_requests_ 中)
//! cached_requests_ 中的请求也要失败回调
for (auto &item : cached_requests_) {
Respond res;
res.http_ver = HttpVer::k1_1;
res.status_code = StatusCode::k503_ServiceUnavailable;
res.body = "connect fail";
if (item.cb) {
++cb_level_;
item.cb(res);
--cb_level_;
}
CHECK_DELETE_RESET_OBJ(item.sp_req);
}
cached_requests_.clear();
if (connect_fail_cb_) {
++cb_level_;
connect_fail_cb_();
--cb_level_;
}
if (!auto_reconnect_) {
state_ = State::kInited;
} else {
state_ = State::kReconnWaiting;
}
}
void Client::Impl::onTcpDisconnected()
{
RECORD_SCOPE();
LogDbg("disconnected");
//! 对所有 pending 请求执行错误回调
failAllPendingRequests(StatusCode::k504_GatewayTimeout, "connection lost");
res_parser_.reset();
if (disconnected_cb_) {
++cb_level_;
disconnected_cb_();
--cb_level_;
}
if (auto_reconnect_) {
state_ = State::kReconnWaiting;
} else {
state_ = State::kInited;
}
}
void Client::Impl::onTcpReceived(Buffer &buff)
{
RECORD_SCOPE();
while (buff.readableSize() > 0) {
size_t rsize = res_parser_.parse(buff.readableBegin(), buff.readableSize());
buff.hasRead(rsize);
if (res_parser_.state() == RespondParser::State::kFinishedAll) {
Respond *sp_respond = res_parser_.getRespond();
if (sp_respond == nullptr) {
LogWarn("getRespond() return nullptr, skip");
continue;
}
if (context_log_enable_)
LogDbg("RES: [%s]", sp_respond->toString().c_str());
//! 取出 pending_requests_ 队首的请求
if (!pending_requests_.empty()) {
auto &pending = pending_requests_.front();
//! 停止超时定时器
if (pending.sp_timer != nullptr) {
pending.sp_timer->disable();
CHECK_DELETE_RESET_OBJ(pending.sp_timer);
}
//! 调用回调
if (pending.cb) {
++cb_level_;
pending.cb(*sp_respond);
--cb_level_;
}
pending_requests_.pop_front();
} else {
LogWarn("no pending request for this respond");
}
delete sp_respond;
} else if (res_parser_.state() == RespondParser::State::kFail) {
LogNotice("parse http respond fail");
failAllPendingRequests(StatusCode::k502_BadGateway, "respond parse fail");
//! 断开连接,让 TcpClient 重连
tcp_client_.stop();
if (auto_reconnect_) {
tcp_client_.start();
state_ = State::kReconnWaiting;
} else {
state_ = State::kInited;
}
break;
} else {
//! 数据不完整,等待更多数据
break;
}
}
}
//! ============ 请求发送 ============
void Client::Impl::sendRequest(const Request &req, const RespondCallback &cb)
{
if (state_ == State::kConnected) {
//! 已连接,直接发送
const string &content = req.toString();
tcp_client_.send(content.data(), content.size());
if (context_log_enable_)
LogDbg("REQ: [%s]", content.c_str());
//! 创建 PendingRequest,加入队列
PendingRequest pending;
pending.req_id = next_req_id_++;
pending.cb = cb;
//! 创建超时定时器
if (request_timeout_ms_.count() > 0) {
auto sp_timer = wp_loop_->newTimerEvent();
sp_timer->initialize(request_timeout_ms_, Event::Mode::kOneshot);
sp_timer->setCallback(bind(&Impl::onRequestTimeout, this, pending.req_id));
sp_timer->enable();
pending.sp_timer = sp_timer;
}
pending_requests_.push_back(pending);
} else {
//! 未连接,缓存请求,等连接建立后发送
CachedRequest cached;
cached.sp_req = new Request(req);
cached.cb = cb;
cached_requests_.push_back(cached);
}
}
void Client::Impl::sendCachedRequests()
{
//! 将缓存中的所有请求发送出去
for (auto &item : cached_requests_) {
sendRequest(*item.sp_req, item.cb);
CHECK_DELETE_RESET_OBJ(item.sp_req);
}
cached_requests_.clear();
}
//! ============ 超时与失败处理 ============
void Client::Impl::onRequestTimeout(int req_id)
{
RECORD_SCOPE();
LogDbg("request %d timeout", req_id);
//! 在 pending_requests_ 中查找该请求
for (auto iter = pending_requests_.begin(); iter != pending_requests_.end(); ++iter) {
if (iter->req_id == req_id) {
//! 构造超时响应
Respond res;
res.http_ver = HttpVer::k1_1;
res.status_code = StatusCode::k408_RequestTimeout;
res.body = "request timeout";
if (iter->cb) {
++cb_level_;
iter->cb(res);
--cb_level_;
}
//! 清理定时器
CHECK_DELETE_RESET_OBJ(iter->sp_timer);
//! 从队列中移除
//! 注意:超时中间的请求被移除后,后续请求仍可正常接收响应
//! 但如果服务器按序回复,中间的请求超时意味着后续请求可能也无法收到响应
//! 这里采用保守策略:仅移除超时的请求,不影响其他请求
pending_requests_.erase(iter);
break;
}
}
}
void Client::Impl::failAllPendingRequests(StatusCode status_code, const string &message)
{
for (auto &item : pending_requests_) {
//! 停止超时定时器
if (item.sp_timer != nullptr) {
item.sp_timer->disable();
CHECK_DELETE_RESET_OBJ(item.sp_timer);
}
//! 构造错误响应
Respond res;
res.http_ver = HttpVer::k1_1;
res.status_code = status_code;
res.body = message;
if (item.cb) {
++cb_level_;
item.cb(res);
--cb_level_;
}
}
pending_requests_.clear();
//! 也处理缓存中的请求
for (auto &item : cached_requests_) {
Respond res;
res.http_ver = HttpVer::k1_1;
res.status_code = status_code;
res.body = message;
if (item.cb) {
++cb_level_;
item.cb(res);
--cb_level_;
}
CHECK_DELETE_RESET_OBJ(item.sp_req);
}
cached_requests_.clear();
}
}
}
}
Loading...
Report
Report success
We will send you the feedback within 2 working days through the letter!
Please fill in the reason for the report carefully. Provide as detailed a description as possible.
Please select a report type
Cancel
Send
误判申诉

此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。

如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。

取消
提交

About

cpp-tbox是一个Linux C++,MIT开源许可的,基于 Reactor 模式的开发框架与组件库。它主要针对智能硬件、机器人、网络服务等开发领域。 它提供了一套易于开发、稳定可靠的框架,有:通信库(TCP/UDP/串口)、HTTP、线程池、定时器池、协程、日志、命令终端、状态机、行为树等非常实用的开发组件,以及完备实用的主框架,能为广大开发者节省大量开发与调试时间。
Cancel

Releases

No release

The Open Source Evaluation Index is derived from the OSS Compass evaluation system, which evaluates projects around the following three dimensions

1. Open source ecosystem

  • Productivity: To evaluate the ability of open-source projects to output software artifacts and open-source value.
  • Innovation: Used to evaluate the degree of diversity of open source software and its ecosystem.
  • Robustness: Used to evaluate the ability of open-source projects to resist internal and external interference and self recover in the face of changing development environments.

2. Collaboration, People, Software

  • Collaboration: represents the degree and depth of collaboration in open source development behavior.
  • Observe the influence of core personnel in open source projects, and examine the evaluations of users and developers on open source projects from a third-party perspective.
  • Software: Evaluate the value of products exported from open-source projects and their ultimate destination. It is also a concrete manifestation of "open source software", one of the oldest mainstream directions in open source evaluation.

3. Evaluation model

    Based on the dimensions of "open source ecosystem" and "collaboration, people, and software", identify quantifiable indicators directly or indirectly related to this goal, quantitatively evaluate the health and ecology of open source projects, and ultimately form an open source evaluation index.

Contributors

All

Activities

can not load any more
Edit
About
Homepage
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C++
1
https://gitee.com/cpp-master/cpp-tbox.git
git@gitee.com:cpp-master/cpp-tbox.git
cpp-master
cpp-tbox
cpp-tbox
develop
Going to Help Center

Search

Comment
Repository Report
Back to the top
Login prompt
This operation requires login to the code cloud account. Please log in before operating.
Go to login
No account. Register

AltStyle によって変換されたページ (->オリジナル) /