文章目录 1 库依赖 2 根据官方示例代码修改封装的WebsocketClient类 2.1 WebsocketClient代码 2.2 WebsocketClient类使用代码 3 Websocket++官方编写客户端示例教程 4 与Websocket++官方示例客户端的不同
1 库依赖 Websocket++/Websocketpp依赖于boost(使用boost 1.74),Websocket++ 0.8.2版本,因为暂时没有使用wss,所以没有集成Openssl。
2 根据官方示例代码修改封装的WebsocketClient类 2.1 WebsocketClient代码 WebsocketClient.h #ifndef WEBSOCKET_CLIENT_H #define WEBSOCKET_CLIENT_H // 不包含TLS Client #include #include // 包含TLS Client // #include // #include #include #include #include #include #include typedef websocketpp::client client; static std::wstring string_to_wstring(const std::string &s) { using default_convert = std::codecvt; static std::wstring_convertconv(new default_convert("CHS")); return conv.from_bytes(s); } static std::string wstring_to_string(const std::wstring &s) { using default_convert = std::codecvt; static std::wstring_convertconv(new default_convert("CHS")); return conv.to_bytes(s); } static std::string ansi_to_utf8(const std::string &s) { static std::wstring_convert conv; return conv.to_bytes(string_to_wstring(s)); } static std::string utf8_to_ansi(const std::string& s) { static std::wstring_convert conv; return wstring_to_string(conv.from_bytes(s)); } // 保存一个连接的metadata class connection_metadata { public: typedef websocketpp::lib::shared_ptr ptr; connection_metadata(websocketpp::connection_hdl hdl, std::string url) : m_Hdl(hdl) , m_Status("Connecting") , m_Url(url) , m_Server("N/A") {} void on_open(client * c, websocketpp::connection_hdl hdl) { m_Status = "Open"; client::connection_ptr con = c->get_con_from_hdl(hdl); m_Server = con->get_response_header("Server"); } void on_fail(client * c, websocketpp::connection_hdl hdl) { m_Status = "Failed"; client::connection_ptr con = c->get_con_from_hdl(hdl); m_Server = con->get_response_header("Server"); m_Error_reason = con->get_ec().message(); } void on_close(client * c, websocketpp::connection_hdl hdl) { m_Status = "Closed"; client::connection_ptr con = c->get_con_from_hdl(hdl); std::stringstream s; s set_close_handler(websocketpp::lib::bind( &connection_metadata::on_close, metadata_ptr, &m_WebsocketClient, websocketpp::lib::placeholders::_1 )); // 注册连接接收消息的Handler con->set_message_handler(websocketpp::lib::bind( &connection_metadata::on_message, metadata_ptr, websocketpp::lib::placeholders::_1, websocketpp::lib::placeholders::_2 )); // 进行连接 m_WebsocketClient.connect(con); std::cout
最近更新
- 深拷贝和浅拷贝的区别(重点)
- 【Vue】走进Vue框架世界
- 【云服务器】项目部署—搭建网站—vue电商后台管理系统
- 【React介绍】 一文带你深入React
- 【React】React组件实例的三大属性之state,props,refs(你学废了吗)
- 【脚手架VueCLI】从零开始,创建一个VUE项目
- 【React】深入理解React组件生命周期----图文详解(含代码)
- 【React】DOM的Diffing算法是什么?以及DOM中key的作用----经典面试题
- 【React】1_使用React脚手架创建项目步骤--------详解(含项目结构说明)
- 【React】2_如何使用react脚手架写一个简单的页面?