#ifndef PELOAD_WEB_SERVER_H #define PELOAD_WEB_SERVER_H #define UNIX #include "mongoose.h" #include #include #include #include #include #include namespace eload { class WebServer { public: WebServer(); ~WebServer(); bool start(int port); void stop(); bool isRunning() const { return m_running; } // 向所有 WebSocket 客户端广播文本 // 线程安全:mongoose 非线程安全,本接口只把文本放入待发队列, // 由 Web 线程在 mg_mgr_poll 返回后统一发送(禁止跨线程直接 mg_ws_send) void broadcast(const std::string& text); // 新客户端连接时调用,返回初始快照 void setOnOpen(std::function handler); // 处理 /api/* 请求:返回 (Content-Type, body)。 // 默认内容类型 application/json;文本/CSV 接口由处理器自行指定。 void setApiHandler(std::function(const std::string& uri, const std::string& query)> handler); private: static bool serverThreadCB(void* pParam); bool serverThreadFunc(); void handleEvent(struct mg_connection* c, int ev, void* ev_data); void flushPending(); struct mg_mgr m_mgr; int m_port = 0; std::atomic m_running{false}; std::thread m_thread; std::mutex m_pendingMutex; std::string m_pending; // latest snapshot to broadcast std::vector m_wsConnections; // web thread only std::function m_onOpen; std::function(const std::string&, const std::string&)> m_apiHandler; }; } // namespace eload #endif // PELOAD_WEB_SERVER_H