您当前的位置: 首页 >  服务器

鱼儿-1226

暂无认证

  • 0浏览

    0关注

    1100博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

C++ - 使用Websocket++编写客户端连接WebSocket服务器并进行通信

鱼儿-1226 发布时间:2021-11-10 13:41:17 ,浏览量:0

文章目录 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

关注
打赏
1604459285
查看更多评论
立即登录/注册

微信扫码登录

0.0405s