#ifndef WEBSOCKETCLIENT_H #define WEBSOCKETCLIENT_H #include #include #include #include #include #include #include #include #include #include typedef websocketpp::client client; class WebSocketClient { public: using message_ptr = websocketpp::config::asio_client::message_type::ptr; using connection_hdl = websocketpp::connection_hdl; using OpenHandler = std::function; using MessageHandler = std::function; using CloseHandler = std::function; using FailHandler = std::function; using PongHandler = std::function; WebSocketClient(); ~WebSocketClient(); // Á¬½Óµ½Ö¸¶¨µÄURI void connect(const std::string& uri); // Ôö¼Ó¿Í»§¶ËµÄ״̬±êʶ bool is_busy() const; void set_busy(bool busy); // ·¢ËÍÎı¾ÏûÏ¢ void send(const std::string& message); // ·¢ËͶþ½øÖÆÊý¾Ý void send_binary(const std::vector& binary_data); // ͨ¹ý¶ÓÁз¢ËÍÎı¾ÏûÏ¢ void enqueue_message(const std::string& message); // ͨ¹ý¶ÓÁз¢ËͶþ½øÖÆÊý¾Ý void enqueue_binary(const std::vector& binary_data); // ´¦ÀíÏÂÒ»¸öÏûÏ¢ void process_next_message(); void process_next_binary(); // ·¢ËÍÎı¾ÏûÏ¢²¢µÈ´ý»Ø¸´ bool send_and_wait(const std::string& message, int timeout_ms); // ·¢ËͶþ½øÖÆÊý¾Ý²¢µÈ´ý»Ø¸´ bool send_binary_and_wait(const std::vector& binary_data, int timeout_ms); // ¹Ø±ÕÁ¬½Ó void close(); // ÉèÖø÷Öֻص÷º¯Êý void set_open_handler(OpenHandler handler); void set_message_handler(MessageHandler handler); void set_close_handler(CloseHandler handler); void set_fail_handler(FailHandler handler); void set_pong_handler(PongHandler handler); // ÉèÖÃÐÄÌø¼ä¸ô£¨µ¥Î»£ºÃ룩 void set_heartbeat_interval(int interval); // »ñÈ¡µ±Ç°Á¬½ÓµÄURL std::string get_current_url(); // ¼ì²éµ±Ç°Á¬½ÓÊÇ·ñÈÔÈ»ÓÐЧ bool is_connected() const; private: // WebSocket ÔËÐк¯Êý void run(); // ÐÄÌø¼ì²éº¯Êý void heartbeat(); // »Øµ÷º¯Êý´¥·¢Æ÷ void on_open(websocketpp::connection_hdl hdl); void on_message(connection_hdl hdl, message_ptr msg); void on_close(websocketpp::connection_hdl hdl); void on_fail(websocketpp::connection_hdl hdl); void on_pong(websocketpp::connection_hdl hdl, const std::string& payload); private: // WebSocket¿Í»§¶ËʵÀý client m_client; // WebSocket Á¬½Ó¾ä±ú connection_hdl m_hdl; // Ïß³ÌÏà¹Ø std::thread m_thread; std::thread m_heartbeat_thread; std::atomic m_connected; std::atomic m_reconnect; int m_heartbeat_interval; bool m_message_received; // ·¢ËͶÓÁÐ std::queue m_message_queue; std::queue> m_binary_queue; // ±êʶ¿Í»§¶ËÊÇ·ñæµ std::atomic m_busy; // Ïß³Ìͬ²½Ïà¹Ø bool m_close_done; std::condition_variable m_cv; // »¥³âËø£¬ÓÃÓÚ±£»¤¹²Ïí×ÊÔ´ std::mutex m_mutex; // »Øµ÷º¯Êý OpenHandler m_open_handler; MessageHandler m_message_handler; CloseHandler m_close_handler; FailHandler m_fail_handler; PongHandler m_pong_handler; }; #endif // WEBSOCKETCLIENT_H