#pragma once #define WIN32_LEAN_AND_MEAN #include #include #include #include #include #include #include #include #include #include #include #include #include "WebSocketHandler.h" namespace beast = boost::beast; namespace http = beast::http; namespace websocket = beast::websocket; namespace net = boost::asio; using tcp = boost::asio::ip::tcp; // 前向声明 class WebSocketSession; class WebServer : public std::enable_shared_from_this { private: net::io_context ioc_; tcp::acceptor acceptor_; std::shared_ptr websocket_handler_; std::thread server_thread_; std::atomic running_; int port_; // 获取静态文件内容 std::string GetStaticFileContent(const std::string& path); // 获取MIME类型 std::string GetMimeType(const std::string& path); // 接受连接 void DoAccept(); // 处理连接 void OnAccept(beast::error_code ec, tcp::socket socket); public: WebServer(int port = 8080, bool use_dll = true); ~WebServer(); // 启动服务器 bool Start(); // 停止服务器 void Stop(); // 检查是否运行中 bool IsRunning() const { return running_; } // 获取WebSocketHandler std::shared_ptr GetWebSocketHandler() { return websocket_handler_; } // HTTP请求处理 void HandleHttpRequest(http::request&& req, std::function)> send); }; // HTTP会话类 class HttpSession : public std::enable_shared_from_this { beast::tcp_stream stream_; beast::flat_buffer buffer_; http::request req_; std::shared_ptr server_; public: explicit HttpSession(tcp::socket&& socket, std::shared_ptr server); void run(); private: void do_read(); void on_read(beast::error_code ec, std::size_t bytes_transferred); void on_write(bool close, beast::error_code ec, std::size_t bytes_transferred); void do_close(); };