WebServer.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. #pragma once
  2. #define WIN32_LEAN_AND_MEAN
  3. #include <windows.h>
  4. #include <winsock2.h>
  5. #include <ws2tcpip.h>
  6. #include <boost/beast/core.hpp>
  7. #include <boost/beast/http.hpp>
  8. #include <boost/beast/websocket.hpp>
  9. #include <boost/asio/ip/tcp.hpp>
  10. #include <boost/asio/strand.hpp>
  11. #include <memory>
  12. #include <string>
  13. #include <thread>
  14. #include <atomic>
  15. #include "WebSocketHandler.h"
  16. namespace beast = boost::beast;
  17. namespace http = beast::http;
  18. namespace websocket = beast::websocket;
  19. namespace net = boost::asio;
  20. using tcp = boost::asio::ip::tcp;
  21. // 前向声明
  22. class WebSocketSession;
  23. class WebServer : public std::enable_shared_from_this<WebServer> {
  24. private:
  25. net::io_context ioc_;
  26. tcp::acceptor acceptor_;
  27. std::shared_ptr<WebSocketHandler> websocket_handler_;
  28. std::thread server_thread_;
  29. std::atomic<bool> running_;
  30. int port_;
  31. // 获取静态文件内容
  32. std::string GetStaticFileContent(const std::string& path);
  33. // 获取MIME类型
  34. std::string GetMimeType(const std::string& path);
  35. // 接受连接
  36. void DoAccept();
  37. // 处理连接
  38. void OnAccept(beast::error_code ec, tcp::socket socket);
  39. public:
  40. WebServer(int port = 8080, bool use_dll = true);
  41. ~WebServer();
  42. // 启动服务器
  43. bool Start();
  44. // 停止服务器
  45. void Stop();
  46. // 检查是否运行中
  47. bool IsRunning() const { return running_; }
  48. // 获取WebSocketHandler
  49. std::shared_ptr<WebSocketHandler> GetWebSocketHandler() { return websocket_handler_; }
  50. // HTTP请求处理
  51. void HandleHttpRequest(http::request<http::dynamic_body>&& req,
  52. std::function<void(http::response<http::dynamic_body>)> send);
  53. };
  54. // HTTP会话类
  55. class HttpSession : public std::enable_shared_from_this<HttpSession> {
  56. beast::tcp_stream stream_;
  57. beast::flat_buffer buffer_;
  58. http::request<http::dynamic_body> req_;
  59. std::shared_ptr<WebServer> server_;
  60. public:
  61. explicit HttpSession(tcp::socket&& socket, std::shared_ptr<WebServer> server);
  62. void run();
  63. private:
  64. void do_read();
  65. void on_read(beast::error_code ec, std::size_t bytes_transferred);
  66. void on_write(bool close, beast::error_code ec, std::size_t bytes_transferred);
  67. void do_close();
  68. };