工程代码地址为:https://download.csdn.net/download/f110300641/10784562
简单的测试:
#include <iostream>
#include <thread>
#include <string>
#include <chrono>
#include "rapidjson/document.h"
#include <rapidjson/writer.h>
#include <rapidjson/stringbuffer.h>
#include <rapidjson/prettywriter.h>
#include "tg_client_mgr.h"
std::string login_json()
{
rapidjson::Document doc;
rapidjson::Document::AllocatorType& Allocator = doc.GetAllocator();
rapidjson::Value root( rapidjson::kObjectType );
rapidjson::Value child( rapidjson::kObjectType );
root.AddMember( "cmd", "login", Allocator );
child.AddMember( "user_name", "COLLECTOR", Allocator );
child.AddMember( "user_pass", "666666", Allocator );
root.AddMember( "data", child, Allocator );
rapidjson::StringBuffer sb;
rapidjson::Writer<rapidjson::StringBuffer> writer( sb );
root.Accept( writer );
return sb.GetString();
}
void callback_fun1(sio::message::ptr const& data)
{
std::cout << "callback_fun1 ";
if(sio::message::flag_object == data->get_flag())
{
auto key_value = data->get_map()["data"];
if(key_value && sio::message::flag_string == key_value->get_flag())
{
std::string strdata = key_value->get_string();
std::cout << "data=" << strdata.c_str() << std::endl;
}
}
}
void test()
{
std::vector<std::string> uri_list;
uri_list.push_back( "ws://192.168.0.105:8086" );
std::map<std::string, tg_client::callback_type> msg_fun_map;
msg_fun_map.insert( std::make_pair( "req_all_data", callback_fun1 ) );
g_client_mgr.build( uri_list, msg_fun_map );
//连接服务器
if ( !g_client_mgr.connect())
{
std::cout << "连接服务器失败" << std::endl;
return;
}
//登录
g_client_mgr.login(login_json());
//通过URI获得某个websocket客户端
auto pClient = g_client_mgr[ uri_list[0] ];
if ( pClient)
{
std::cout << "uri=" << pClient->get_uri() << std::endl;
}
}
int main()
{
test();
while ( true )
{
std::this_thread::sleep_for( std::chrono::milliseconds( 100 ) );
}
return 0;
}
其中sio_socket的git地址为:https://github.com/socketio/socket.io-client-cpp