Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion doc/multiloop-design.md
Original file line number Diff line number Diff line change
Expand Up @@ -677,7 +677,7 @@ W4 之后改成了**连接自己那条**(`client->get_loop()`),分片用

**理由要写准(2026-09-22 按源码核过,原先那句不成立)**:不能说成"在**别的循环的线程**上
`delete` 一个持有那条循环句柄的 `uvcpp_ws_connection` 在 libuv 层面不成立" ——
`notify_retired()`(`src/web/uvcpp_ws_connection.cpp:115-143`)在对象进 `retired_` **之前**
`notify_retired()`(`src/web/uvcpp_ws_connection.cpp:115-154`)在对象进 `retired_` **之前**
就跑完了:它清零 `close_observer_id_`、摘掉关闭观察者、把 `tcp_` 置空
(`src/web/uvcpp_ws_connection.cpp:133`);而 `~uvcpp_ws_connection`
(`src/web/uvcpp_ws_connection.cpp:35-48`)在 `tcp_ == nullptr` 时
Expand Down
84 changes: 42 additions & 42 deletions doc/web-ws-guide.md

Large diffs are not rendered by default.

33 changes: 33 additions & 0 deletions doc/webapp-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
18. [已知限制](#18-已知限制)
19. [横向扩展:多循环(`set_loops`)](#19-横向扩展多循环set_loops)
20. [可观测性:`/health` / `/ready` / `/metrics`](#20-可观测性health--ready--metrics)
21. [WebSocket 房间与广播](#21-websocket-房间与广播)

---

Expand Down Expand Up @@ -1568,6 +1569,38 @@ reg.register_gauge("db_pool_in_use", "Borrowed connections",

---

## 21. WebSocket 房间与广播

`uvcpp_ws_rooms`(`#include <webapp/uvcpp_ws_rooms.h>`)把三件事收在一起:
`join/leave`、按房间群发、慢客户端策略。

```cpp
// doc-snippet: fragment — 装配摘录,不是完整翻译单元。
uvcpp::uvcpp_ws_rooms rooms; // 活得比所有会话久(归 app 所有)

app.websocket("/chat/:room", [&](uvcpp::uvcpp_web_ws_request& ws_req) {
uvcpp::uvcpp_ws_connection* c = ws_req.connection();
rooms.join(c, *ws_req.param("room"));
});

// 从别的线程(例如定时任务)广播:用 app.post() 投回循环线程
rooms.broadcast_text("lobby", msg.data(), msg.size());
```

- **断线自动退订**:`join()` 会给会话挂一个终结观察者
(`uvcpp_ws_connection::add_close_observer()`),对端 Close、异常断开、
协议错误、本端 `close()`、服务器停机 —— 任何一条终结路径都会把它从所有
房间摘掉。业务不需要再手写"on_close 清理"。
- **慢客户端**:单条连接发送积压 > `uvcpp_ws_broadcast_options::max_queue_bytes`
(默认 1 MiB)时,按 `policy` 处理:`DROP`(跳过这一条,默认)或
`CLOSE`(1001 关掉)。广播返回值 + `stats()` 里的 `dropped` / `closed_slow`
如实记账;一条不读数据的连接拖不慢整场广播。
- **只在 app 的循环线程上调用**(房间表没有锁);跨线程用 `app.post()`。
- 只接 **h1** 会话;跨进程(Redis pub/sub)见 issue #74。用例:
`web_app_ws_rooms_func.cpp`。

---

## 可运行示例

`examples/webapp_demo.cpp` —— 默认**自校验**:起一个 app(路由 + 中间件 + 静态 +
Expand Down
33 changes: 32 additions & 1 deletion src/web/uvcpp_ws_connection.cpp
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#include <web/uvcpp_ws_connection.h>
#include <web/uvcpp_ws_connection.h>

#include <random>
#if UVCPP_WEB_ENABLE
Expand Down Expand Up @@ -135,6 +135,17 @@ void uvcpp_ws_connection::notify_retired() {
// 队列里的帧发不出去了,逐条结算 —— 不结算调用方会永远等下去。
if (!send_q_.empty()) fail_pending_sends(-1);

// 终结观察者:在属主回收**之前**跑,且必须是本对象还能安全访问的最后一段
// 里的一步(回调里可能把本对象从房间表里摘掉,但不该再调本类别的发送方法)。
if (!close_observers_.empty()) {
std::map<int, std::function<void()>> obs;
obs.swap(close_observers_);
for (std::map<int, std::function<void()>>::iterator it = obs.begin();
it != obs.end(); ++it) {
if (it->second) it->second();
}
}

// 上报属主。回调返回之后本对象随时可能被 delete,所以这必须是最后一步,
// 并且先把回调搬出来(属主的 delete 会销毁 retire_fn_ 自己)。
retire_fn cb(std::move(retire_fn_));
Expand Down Expand Up @@ -706,6 +717,26 @@ void uvcpp_ws_connection::on_pong(std::function<void(const uint8_t*, size_t)> cb
void uvcpp_ws_connection::on_close(std::function<void(ws_close_code, const std::string&)> cb) { on_close_ = std::move(cb); }
void uvcpp_ws_connection::on_error(std::function<void(int, const std::string&)> cb) { on_error_ = std::move(cb); }

int uvcpp_ws_connection::add_close_observer(std::function<void()> cb) {
if (!cb) return 0;
const int id = close_observer_next_id_++;
close_observers_[id] = std::move(cb);
return id;
}

void uvcpp_ws_connection::remove_close_observer(int id) {
close_observers_.erase(id);
}

size_t uvcpp_ws_connection::pending_send_bytes() const {
size_t n = 0;
for (std::deque<pending_send>::const_iterator it = send_q_.begin();
it != send_q_.end(); ++it) {
n += it->bytes.size();
}
return n;
}

void uvcpp_ws_connection::on_frame(std::function<void(const uvcpp_ws_frame&)> cb) {
on_frame_ = std::move(cb);
}
Expand Down
28 changes: 28 additions & 0 deletions src/web/uvcpp_ws_connection.h
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
#include <cstddef>
#include <deque>
#include <functional>
#include <map>
#include <memory>
#include <string>
#include <uvcpp/uvcpp_define.h>
Expand Down Expand Up @@ -200,6 +201,29 @@ class UVCPP_API uvcpp_ws_connection {
*/
void on_close(std::function<void(ws_close_code, const std::string&)> cb);

/**
* @brief 追加一个「会话终结」观察者。**可叠加**,与 `on_close` 不同。
*
* `on_close` 只有一个槽,而且只在**对端**走人时报告;本方法在任何一条终结
* 路径上(对端 Close、异常断开、本端 `close()`、协议错误、属主 `terminate()`)
* 都**恰好触发一次**。房间订阅表这类"必须精确摘除"的簿记靠它。
*
* 回调在终结那一刻**同步**跑;返回之后不要再碰会话(它可能被回收)。
*
* @return 观察者 id(`remove_close_observer()` 用);0 = 无效参数。
*/
int add_close_observer(std::function<void()> cb);

/// 摘掉一个观察者。会话已经终结时是空操作。
void remove_close_observer(int id);

/**
* @brief 发送队列里**还没写完**的字节数(含已在途的那一批)。
*
* 广播的"慢客户端"策略用它判定——本层没有别的公开积压指标。
*/
size_t pending_send_bytes() const;

/**
* @brief 协议错误回调:`on_error(close_code, reason)`。
*
Expand Down Expand Up @@ -371,6 +395,10 @@ class UVCPP_API uvcpp_ws_connection {
bool close_notified_ = false;
retire_fn retire_fn_;

/// 会话终结观察者;id → 回调。见 `add_close_observer()`。
std::map<int, std::function<void()>> close_observers_;
int close_observer_next_id_ = 1;

/**
* @brief 存活令牌(与 `uvcpp_tcp_client::alive_token_` 同一个手法)。
*
Expand Down
Loading
Loading