websocket

This commit is contained in:
2026-07-27 16:16:03 +08:00
parent 5aee257257
commit b8f8080325
5 changed files with 306 additions and 54 deletions
@@ -51,6 +51,24 @@ void WebSocket_Manager::push_data(const char *buf, uint64_t len) {
conn->send(buf, len, drogon::WebSocketMessageType::Binary);
}
}
void WebSocket_Manager::set_message_handler(Message_Handler handler) {
message_handler = std::move(handler);
}
void WebSocket_Manager::set_close_handler(Close_Handler handler) {
close_handler = std::move(handler);
}
void WebSocket_Manager::handle_message(const drogon::WebSocketConnectionPtr &conn,
std::string &&message,
const drogon::WebSocketMessageType &type) {
if (message_handler) {
message_handler(conn, std::move(message), type);
}
}
void WebSocket_Manager::handle_close(const drogon::WebSocketConnectionPtr &conn) {
if (close_handler) {
close_handler(conn);
}
}
size_t WebSocket_Manager::get_websocket_connect_num() {
std::lock_guard<std::mutex> g(mtx);
return connections.size();
@@ -77,14 +95,24 @@ std::shared_ptr<WebSocket_Manager> Ws_Mgr::get_ws(std::string_view path) {
return nullptr;
}
void DSP_Ws_Mgr::handleNewMessage(const drogon::WebSocketConnectionPtr &,
std::string &&,
const drogon::WebSocketMessageType &) {}
void DSP_Ws_Mgr::handleNewMessage(const drogon::WebSocketConnectionPtr &conn,
std::string &&message,
const drogon::WebSocketMessageType &type) {
auto &s = conn->getContextRef<WebSocket_Connection>();
auto ws = Ws_Mgr::instance()->get_ws(s.type);
if (ws) {
ws->handle_message(conn, std::move(message), type);
}
}
void DSP_Ws_Mgr::handleConnectionClosed(
const drogon::WebSocketConnectionPtr &conn) {
auto &s = conn->getContextRef<WebSocket_Connection>();
auto rp = s.type;
auto ws = Ws_Mgr::instance()->get_ws(rp);
if (!ws) {
return;
}
ws->handle_close(conn);
// LOG_DEBUG
std::ostringstream oss;
oss << "已有连接数:" << ws->get_websocket_connect_num() << " "
@@ -100,6 +128,10 @@ void DSP_Ws_Mgr::handleNewConnection(
auto rpt = req->path();
auto rp = rpt.substr(std::string("/ws").size());
auto ws = Ws_Mgr::instance()->get_ws(rp);
if (!ws) {
conn->shutdown();
return;
}
std::ostringstream oss;
oss << "已有连接数:" << ws->get_websocket_connect_num() << " "
<< "新建websocket连接:" << rp << " "