解决了websock频繁连接的问题

This commit is contained in:
zjk
2025-05-17 08:39:18 +08:00
parent ac4301f99e
commit 8585f0dd51
7 changed files with 34 additions and 3008 deletions
+33 -5
View File
@@ -4,6 +4,7 @@
#include "mongoose.h"
#include <iostream>
#include "json/json.h"
#include <sys/resource.h>
using json = Json::Value;
@@ -11,26 +12,53 @@ using json = Json::Value;
void HttpServer::handleWebSocketEvent(struct mg_connection* c, int ev, void* ev_data, void* fn_data) {
HttpServer* server = static_cast<HttpServer*>(fn_data);
if (ev == MG_EV_OPEN) {
// 新连接建立
if (ev == MG_EV_WS_OPEN) {
// WebSocket连接成功建立
std::lock_guard<std::mutex> lock(server->ws_connections_mutex_);
server->ws_connections_.push_back(c);
LOG_F(INFO, "WebSocket connection opened: id=%lu fd=%d", c->id, c->fd);
LOG_F(INFO, "WebSocket connection established: id=%lu fd=%d", c->id, c->fd);
} else if (ev == MG_EV_CLOSE || ev == MG_EV_ERROR) {
// 连接关闭或错误
std::lock_guard<std::mutex> lock(server->ws_connections_mutex_);
auto it = std::find(server->ws_connections_.begin(), server->ws_connections_.end(), c);
if (it != server->ws_connections_.end()) {
LOG_F(ERROR, "WebSocket %s: id=%lu fd=%d",
ev == MG_EV_ERROR ? "error" : "closed", c->id, c->fd);
if (ev == MG_EV_ERROR) {
struct mg_http_message *hm = (struct mg_http_message *) ev_data;
if (errno != 0) {
LOG_F(ERROR, "WebSocket error: id=%lu fd=%d, errno=%d",
c->id, c->fd, errno);
// 打印socket错误信息
char buf[256];
strerror_r(errno, buf, sizeof(buf));
LOG_F(ERROR, "Socket error: %s", buf);
} else {
LOG_F(ERROR, "WebSocket connection closed abnormally: id=%lu fd=%d",
c->id, c->fd);
}
} else {
LOG_F(INFO, "WebSocket closed: id=%lu fd=%d", c->id, c->fd);
}
server->ws_connections_.erase(it);
// 检查系统资源限制
static int fd_limit_checked = 0;
if (!fd_limit_checked) {
fd_limit_checked = 1;
struct rlimit lim;
if (getrlimit(RLIMIT_NOFILE, &lim) == 0) {
LOG_F(INFO, "File descriptor limits: soft=%lu hard=%lu",
lim.rlim_cur, lim.rlim_max);
}
}
}
} else if (ev == MG_EV_HTTP_MSG) {
// HTTP请求处理
struct mg_http_message *hm = (struct mg_http_message *) ev_data;
if (mg_match(hm->uri, mg_str("/ws"), NULL)) {
// 升级到WebSocket连接
LOG_F(INFO, "Upgrading to WebSocket: id=%lu fd=%d", c->id, c->fd);
mg_ws_upgrade(c, hm, nullptr);
LOG_F(INFO, "WebSocket upgrade completed: id=%lu fd=%d", c->id, c->fd);
} else {
// 返回主页HTML
mg_http_reply(c, 200, "Content-Type: text/html; charset=utf-8\r\n", INDEX_HTML.c_str());