| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- #pragma once
- #define WIN32_LEAN_AND_MEAN
- #include <windows.h>
- #include <winsock2.h>
- #include <ws2tcpip.h>
- #include <boost/beast/core.hpp>
- #include <boost/beast/http.hpp>
- #include <boost/beast/websocket.hpp>
- #include <boost/asio/ip/tcp.hpp>
- #include <boost/asio/strand.hpp>
- #include <memory>
- #include <string>
- #include <thread>
- #include <atomic>
- #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<WebServer> {
- private:
- net::io_context ioc_;
- tcp::acceptor acceptor_;
- std::shared_ptr<WebSocketHandler> websocket_handler_;
- std::thread server_thread_;
- std::atomic<bool> 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<WebSocketHandler> GetWebSocketHandler() { return websocket_handler_; }
-
- // HTTP请求处理
- void HandleHttpRequest(http::request<http::dynamic_body>&& req,
- std::function<void(http::response<http::dynamic_body>)> send);
- };
- // HTTP会话类
- class HttpSession : public std::enable_shared_from_this<HttpSession> {
- beast::tcp_stream stream_;
- beast::flat_buffer buffer_;
- http::request<http::dynamic_body> req_;
- std::shared_ptr<WebServer> server_;
-
- public:
- explicit HttpSession(tcp::socket&& socket, std::shared_ptr<WebServer> 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();
- };
|