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
/
server
/
server_imp.cpp
cpp-tbox
/
modules
/
http
/
server
/
server_imp.cpp
server_imp.cpp 11.21 KB
Copy Edit Raw Blame History
海卫哥 authored 2026年06月29日 15:45 +08:00 . !53 feat(http): 实现 HTTP SSE 服务端的功能
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
/*
* .============.
* // M A K E / \
* // C++ DEV / \
* // E A S Y / \/ \
* ++ ----------. \/\ .
* \\ \ \ /\ /
* \\ \ \ /
* \\ \ \ /
* -============'
*
* Copyright (c) 2018 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 "server_imp.h"
#include <algorithm>
#include <tbox/base/log.h>
#include <tbox/base/assert.h>
#include <tbox/base/wrapped_recorder.h>
#include <tbox/util/buffer.h>
#include <tbox/network/tcp_connection.h>
#include "middleware.h"
namespace tbox {
namespace http {
namespace server {
using namespace std;
using namespace std::placeholders;
using namespace event;
using namespace network;
Server::Impl::Impl(Server *wp_parent, Loop *wp_loop)
: wp_parent_(wp_parent)
, wp_loop_(wp_loop)
, tcp_server_(wp_loop)
{ }
Server::Impl::~Impl()
{
TBOX_ASSERT(cb_level_ == 0);
cleanup();
}
bool Server::Impl::initialize(const network::SockAddr &bind_addr, int listen_backlog)
{
if (!tcp_server_.initialize(bind_addr, listen_backlog))
return false;
tcp_server_.setConnectedCallback(bind(&Impl::onTcpConnected, this, _1));
tcp_server_.setReceiveCallback(bind(&Impl::onTcpReceived, this, _1, _2), 0);
tcp_server_.setSendCompleteCallback(bind(&Impl::onTcpSendCompleted, this, _1));
state_ = State::kInited;
return true;
}
bool Server::Impl::setTlsConfig(const network::TlsConfig &config)
{
return tcp_server_.setTlsConfig(config);
}
bool Server::Impl::start()
{
if (tcp_server_.start()) {
state_ = State::kRunning;
return true;
}
return false;
}
void Server::Impl::stop()
{
if (state_ == State::kRunning) {
tcp_server_.stop();
state_ = State::kInited;
}
}
void Server::Impl::cleanup()
{
if (state_ != State::kNone) {
stop();
mw_cabinet_.foreach([](RequestHandler *ptr) { delete ptr; });
mw_cabinet_.clear();
mw_order_.clear();
tcp_server_.cleanup();
state_ = State::kNone;
}
}
MiddlewareToken Server::Impl::use(RequestHandler &&handler)
{
if (cb_level_ > 0) {
LogWarn("不能在 next 链中调用 use(),请使用 Loop 的 runNext() 来处理");
return MiddlewareToken();
}
auto token = mw_cabinet_.alloc(new RequestHandler(std::move(handler)));
mw_order_.push_back(token);
return token;
}
MiddlewareToken Server::Impl::use(Middleware *wp_middleware)
{
if (cb_level_ > 0) {
LogWarn("不能在 next 链中调用 use(),请使用 Loop 的 runNext() 来处理");
return MiddlewareToken();
}
auto token = mw_cabinet_.alloc(new RequestHandler(bind(&Middleware::handle, wp_middleware, _1, _2)));
mw_order_.push_back(token);
return token;
}
bool Server::Impl::unuse(const MiddlewareToken &token)
{
if (cb_level_ > 0) {
LogWarn("不能在 next 链中调用 unuse(),请使用 Loop 的 runNext() 来处理");
return false;
}
//! 从 Cabinet 中释放
RequestHandler *handler = mw_cabinet_.free(token);
if (handler == nullptr)
return false; //! token 无效或已释放
delete handler;
//! 从 order 中删除该 token(低频 O(n) 操作)
auto iter = find(mw_order_.begin(), mw_order_.end(), token);
if (iter != mw_order_.end())
mw_order_.erase(iter);
return true;
}
void Server::Impl::onTcpConnected(const TcpServer::ConnToken &ct)
{
RECORD_SCOPE();
auto conn = new Connection;
tcp_server_.setContext(ct, conn,
[](void* ptr) {
auto conn = static_cast<Connection*>(ptr);
CHECK_DELETE_OBJ(conn);
}
);
}
namespace {
bool IsLastRequest(const Request *req)
{
auto iter = req->headers.find("Connection");
if (req->http_ver == HttpVer::k1_0) {
//! 1.0 版本默认为一连接一请求,需要特定的 Connection: Keep-Alive 才能持处
if (iter == req->headers.end()) {
return true;
} else {
return iter->second.find("keep-alive") == std::string::npos;
}
} else {
//! 否则为 1.1 及以上的版本,默认为持久连接;除非出现 Connection: close
if (iter == req->headers.end()) {
return false;
} else {
return iter->second.find("close") != std::string::npos;
}
}
}
}
void Server::Impl::onTcpReceived(const TcpServer::ConnToken &ct, Buffer &buff)
{
RECORD_SCOPE();
Connection *conn = static_cast<Connection*>(tcp_server_.getContext(ct));
TBOX_ASSERT(conn != nullptr);
//! 如果已被标记为最后的请求,就不应该再有请求来
if (conn->close_index != numeric_limits<int>::max()) {
buff.hasReadAll();
LogWarn("should not recv any data");
return;
}
//! 如果已被标记为升级请求,停止解析 HTTP 数据
if (conn->is_upgrade) {
//! 不消费剩余数据,留给升级后的协议处理
return;
}
while (buff.readableSize() > 0) {
size_t rsize = conn->req_parser.parse(buff.readableBegin(), buff.readableSize());
buff.hasRead(rsize);
if (conn->req_parser.state() == RequestParser::State::kFinishedAll) {
Request *req = conn->req_parser.getRequest();
if (context_log_enable_)
LogDbg("REQ: [%s]", req->toString().c_str());
auto sp_ctx = make_shared<Context>(wp_parent_, ct, conn->req_index++, req);
handle(sp_ctx, 0);
//! 检查是否有协议升级回调(WebSocket、SSE 等)
//! 如果有,标记连接为升级模式,停止继续解析 HTTP 数据
if (sp_ctx->res().upgrade_cb) {
conn->is_upgrade = true;
//! 升级请求:保留 buffer 中未消费的数据,留给升级后的协议
break;
}
//! 非升级请求:检查是否为最后一个请求
if (IsLastRequest(req)) {
conn->close_index = conn->req_index;
LogDbg("mark close at %d", conn->close_index);
tcp_server_.shutdown(ct, SHUT_RD);
}
} else if (conn->req_parser.state() == RequestParser::State::kFail) {
LogNotice("parse http from %s fail", tcp_server_.getClientAddress(ct).toString().c_str());
tcp_server_.disconnect(ct);
break;
} else {
break;
}
}
}
void Server::Impl::onTcpSendCompleted(const TcpServer::ConnToken &ct)
{
RECORD_SCOPE();
if (!tcp_server_.isClientValid(ct))
return;
Connection *conn = static_cast<Connection*>(tcp_server_.getContext(ct));
TBOX_ASSERT(conn != nullptr);
//! 如果最后一个已完成发送,则断开连接
if (conn->res_index > conn->close_index)
tcp_server_.disconnect(ct);
}
/**
* 为了保证管道化连接中Respond与Request的顺序一致性,要做特殊处理。
* 如果所提交的index不是当前需要回复的res_index,那么就先暂存起来,等前面的发送完成后再发送;
* 如果是,则可以直接回复。然后再将暂存中的未发送的其它数据也一同发送。
*
* 对于协议升级请求(WebSocket 101、SSE 200 等),发送完响应后,
* 将从HTTP服务器分离TcpConnection,并通过Respond::upgrade_cb回调交给升级协议。
*/
void Server::Impl::commitRespond(const TcpServer::ConnToken &ct, int index, Respond *res)
{
RECORD_SCOPE();
if (!tcp_server_.isClientValid(ct)) {
delete res;
return;
}
//! 处理协议升级请求(WebSocket 101、SSE 200 等)
//! 触发条件:res->upgrade_cb 已设置(中间件负责设置)
if (res->upgrade_cb) {
//! 注意:必须在 std::move(upgrade_cb) 之前调用 toString()
//! 否则 move 后 upgrade_cb 为空,toString() 会误判为普通响应而添加 Content-Length
//! SSE 响应添加 Content-Length:0 会导致浏览器认为响应已完成并断开重连
const string content = res->toString();
//! 发送响应后,将 TcpConnection 从 HTTP 服务器分离,交给升级协议
auto upgrade_cb = std::move(res->upgrade_cb);
delete res;
tcp_server_.send(ct, content.data(), content.size());
if (context_log_enable_)
LogDbg("RES: [%s]", content.c_str());
//! 当前回调结束后立即执行 detach(使用 runNext,更高效)
//! 因为 commitRespond() 是在 Loop 线程中执行的
wp_loop_->runNext([this, ct, upgrade_cb] {
TcpConnection *tcp_conn = tcp_server_.detachConnection(ct);
if (tcp_conn != nullptr)
upgrade_cb(tcp_conn);
else
LogWarn("tcp_conn == nullptr");
}, "HttpUpgrade: detach connection");
return;
}
Connection *conn = static_cast<Connection*>(tcp_server_.getContext(ct));
TBOX_ASSERT(conn != nullptr);
if (index == conn->res_index) {
//! 将当前的数据直接发送出去
{
const string &content = res->toString();
tcp_server_.send(ct, content.data(), content.size());
delete res;
if (context_log_enable_)
LogDbg("RES: [%s]", content.c_str());
}
++conn->res_index;
//! 如果当前这个回复是最后一个,则不需要发送缓存中的数据
if (conn->res_index > conn->close_index)
return;
//! 尝试发送 conn->res_buff 缓冲中的数据
auto &res_buff = conn->res_buff;
auto iter = res_buff.find(conn->res_index);
while (iter != res_buff.end()) {
Respond *res = iter->second;
{
const string &content = res->toString();
tcp_server_.send(ct, content.data(), content.size());
delete res;
if (context_log_enable_)
LogDbg("RES: [%s]", content.c_str());
}
res_buff.erase(iter);
++conn->res_index;
//! 如果当前这个回复是最后一个,则不需要再发送缓存中的数据
if (conn->res_index > conn->close_index)
return;
iter = res_buff.find(conn->res_index);
}
} else {
//! 放入到 conn.res_buff 中暂存
conn->res_buff[index] = res;
}
}
void Server::Impl::handle(ContextSptr sp_ctx, size_t index)
{
RECORD_SCOPE();
if (index >= mw_order_.size())
return;
auto token = mw_order_.at(index);
RequestHandler *handler_ptr = mw_cabinet_.at(token);
if (handler_ptr && *handler_ptr) {
++cb_level_;
(*handler_ptr)(sp_ctx, std::bind(&Impl::handle, this, sp_ctx, index + 1));
--cb_level_;
} else {
//! handler 已被移除或为空,跳过,执行下一个
handle(sp_ctx, index + 1);
}
}
Server::Impl::Connection::~Connection()
{
//! 一定要记得清除非发送的Respond
for (auto & item : res_buff)
delete item.second;
}
}
}
}
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 によって変換されたページ (->オリジナル) /