1
0

wsClient.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. #include "wsClient.h"
  2. #include "constdef.h"
  3. #include <thread>
  4. #include <chrono>
  5. #include <boost/locale.hpp>
  6. #include "log.h"
  7. #include "common_tool.h"
  8. namespace sys
  9. {
  10. const int _LOGIN_SLEEP_TIME_ = 500;//登录前的等待时间(单位:毫秒)
  11. const int _OPEN_SOCKET_WAIT_TIME_ = 100;//等待打开socket时间(单位:毫秒)
  12. wsClient::wsClient()
  13. {
  14. __ID = 0;
  15. _reset();
  16. }
  17. wsClient::~wsClient()
  18. {
  19. __wsclient.sync_close();
  20. }
  21. void wsClient::_reset()
  22. {
  23. __Connected = false;
  24. __SktOpened = false;
  25. __Logined = false;
  26. }
  27. static void beatheart(int, std::string const&, sio::message::ptr const&, bool, sio::message::list & )
  28. {
  29. }
  30. std::shared_ptr<wsClient> wsClient::clone()
  31. {
  32. std::shared_ptr<wsClient> ret=std::make_shared<wsClient>();
  33. ret->__ID = __ID;
  34. ret->__uri = __uri;
  35. ret->__MsgFuncList = __MsgFuncList;
  36. return ret;
  37. }
  38. void wsClient::init( int ID, const std::string & uri, const std::map<std::string, MSG_HANDLE_FUNC_TYPE>& MsgFuncList )
  39. {
  40. __ID = ID;
  41. __uri = uri;
  42. __MsgFuncList = MsgFuncList;
  43. //MsgFuncList.insert( std::make_pair( "beatheart", &web_connect::_beatheart_callback ) );
  44. __MsgFuncList.insert(std::make_pair("beatheart",&beatheart));
  45. }
  46. std::string wsClient::get_uri()
  47. {
  48. return __uri;
  49. }
  50. int wsClient::connect( int time_out )
  51. {
  52. if ( __uri.empty() )
  53. {
  54. __LastError = "Error, uri is empty.";
  55. return -1;
  56. }
  57. {
  58. __wsclient.set_reconnect_attempts( 0 );
  59. using std::placeholders::_1;
  60. using std::placeholders::_2;
  61. using std::placeholders::_3;
  62. using std::placeholders::_4;
  63. sio::socket::ptr sock = __wsclient.socket();
  64. __recv_ping_time = 0;
  65. __connet_time = 0;
  66. __wsclient.set_open_listener( std::bind( &wsClient::_on_connected, this ) );
  67. __wsclient.set_close_listener( std::bind( &wsClient::_on_close, this, std::placeholders::_1 ) );
  68. __wsclient.set_reconnect_listener( std::bind( &wsClient::_on_reconnect, this, std::placeholders::_1, std::placeholders::_2 ) );
  69. __wsclient.set_fail_listener( std::bind( &wsClient::_on_fail, this ) );
  70. __wsclient.set_socket_open_listener( std::bind( &wsClient::_on_socket_opened, this ) );
  71. sock->on( JSON_CMD_VALUE_CALL, sio::socket::event_listener_aux( std::bind( &wsClient::_OnCallMessage, this, _1, _2, _3, _4 ) ) );
  72. sock->on( "code", sio::socket::event_listener_aux( std::bind( &wsClient::_OnLoginResponse, this, _1, _2, _3, _4 ) ) );
  73. }
  74. __wsclient.connect( __uri );
  75. std::cv_status status = std::cv_status::timeout;
  76. int nRet = -1;
  77. __lock.lock();
  78. if ( !IsConnected() )
  79. {
  80. status = __cond.wait_for( __lock, std::chrono::seconds( time_out ) );
  81. if ( std::cv_status::timeout == status )
  82. {
  83. __LastError = "Failed to connect server.";
  84. nRet = -1;
  85. }
  86. else
  87. {
  88. unsigned int cur_time = time(0);
  89. __connet_time = cur_time;
  90. __recv_ping_time = cur_time;
  91. nRet = 0;
  92. }
  93. }
  94. else
  95. {
  96. nRet = 0;
  97. }
  98. __lock.unlock();
  99. return nRet;
  100. }
  101. void wsClient::login()
  102. {
  103. if ( !IsConnected() )
  104. {
  105. __LastError = "please connect server before login!";
  106. return;
  107. }
  108. //std::cv_status status = std::cv_status::timeout;
  109. __lock.lock();
  110. if ( !IsSktOpened() )
  111. {
  112. // status =
  113. __cond.wait_for( __lock, std::chrono::milliseconds( _OPEN_SOCKET_WAIT_TIME_ ) );
  114. }
  115. __lock.unlock();
  116. if ( !IsSktOpened() )
  117. {
  118. __LastError = "socket is not opened before login!";
  119. return;
  120. }
  121. std::this_thread::sleep_for( std::chrono::milliseconds( _LOGIN_SLEEP_TIME_ ) );
  122. sys::_JS_LOGIN_ Login;
  123. Login.user_name = JSON_VALUE_USERNAME;
  124. Login.user_password = JSON_VALUE_PASSWORD;
  125. std::string strLogin = __jsBuilder.BuildLogin( Login );
  126. log_info("send2web: cmd=%s, data=%s", JSON_CMD_VALUE_USER, strLogin.c_str());
  127. strLogin += "\n";
  128. sio::socket::ptr skt_ptr;
  129. skt_ptr = __wsclient.socket();
  130. skt_ptr->emit( JSON_CMD_VALUE_USER, strLogin, [this]( sio::message::list const& msglist )
  131. {
  132. int nRet = 0;
  133. char szError[512] = { 0 };
  134. sio::message::ptr msg_ptr = msglist[0];
  135. nRet = ( int ) msg_ptr->get_map()["code"]->get_int();
  136. if ( 0 == nRet )
  137. {
  138. __Logined = true;
  139. }
  140. else
  141. {
  142. __Logined = false;
  143. sprintf( szError, "Login failed,code=%d", nRet );
  144. __LastError = szError;
  145. }
  146. } );
  147. }
  148. void wsClient::_on_connected()
  149. {
  150. __lock.lock();
  151. __cond.notify_all();
  152. __Connected = true;
  153. __lock.unlock();
  154. }
  155. void wsClient::send( const std::string & Cmd, const std::string & Data )
  156. {
  157. std::lock_guard<std::recursive_mutex> lock( __send_lock );
  158. sio::socket::ptr skt_ptr;
  159. skt_ptr = __wsclient.socket();
  160. skt_ptr->emit( Cmd, Data );
  161. }
  162. void wsClient::_on_close( sio::client::close_reason const & reason )
  163. {
  164. log_info("websocket %d close()",__ID);
  165. _reset();
  166. // 启动重连线程,尝试每隔10s连接一次,连接成功就事件阻塞
  167. //reconnect();
  168. }
  169. void wsClient::_on_reconnect( unsigned p1, unsigned p2 )
  170. {
  171. log_info("websocket %d reconnect()",__ID);
  172. _reset();
  173. }
  174. void wsClient::_on_fail()
  175. {
  176. _reset();
  177. }
  178. void wsClient::_on_socket_opened()
  179. {
  180. __SktOpened = true;
  181. }
  182. void wsClient::_OnCallMessage( std::string const& name, sio::message::ptr const& data, bool need_ack, sio::message::list &ack_resp )
  183. {
  184. // 接收web传送的json
  185. if(data->to_string() == ""){
  186. log_info("web-message: recv web send message is null!");
  187. return;
  188. }
  189. log_info("web-message:%s", data->to_string().c_str());
  190. if ( data->get_flag() == sio::message::flag_object )
  191. {
  192. std::string cmd = data->get_map()[JSON_ROOT_KEY_CMD]->get_string();
  193. std::map<std::string, MSG_HANDLE_FUNC_TYPE>::iterator mit_func;
  194. mit_func = __MsgFuncList.find( cmd );
  195. if ( mit_func != __MsgFuncList.end() )
  196. {
  197. try
  198. {
  199. mit_func->second( GetID(), name, data, need_ack, ack_resp );
  200. }
  201. catch(const std::exception&e)
  202. {
  203. log_error("捕获到异常:%s",e.what());
  204. }
  205. catch(...)
  206. {
  207. log_error("捕获到未知异常");
  208. }
  209. }
  210. else
  211. {
  212. log_error("web-message没有找到对应的处理函数:%s",data->to_string().c_str());
  213. }
  214. __recv_ping_time = time(0);
  215. }else if(data->get_flag() == sio::message::flag_string){
  216. rapidjson::Document doc;
  217. int len = data->to_string().length();
  218. std::string str = data->to_string().substr(1, len-2);
  219. //log_info("web-message: begin parse...");
  220. doc.Parse(str.c_str());
  221. //log_info("web-message: end parse...");
  222. if(!doc.HasParseError()){
  223. std::string cmd = doc[JSON_ROOT_KEY_CMD].GetString();
  224. auto mit_func = __MsgFuncList.find(cmd);
  225. log_info("web-message: cmd=%s, type=%d, msg=%s", cmd.c_str(), data->get_flag(),data->to_string().c_str());
  226. if(mit_func != __MsgFuncList.end()){
  227. sio::message::ptr msg = to_sio_message(str);
  228. mit_func->second(GetID(), name, msg, need_ack, ack_resp);
  229. /*sio::message::ptr msg;
  230. if(cmd == "call_card_req"){
  231. msg = call_to_sio_message(str);
  232. }else{
  233. msg = to_sio_message(str);
  234. }
  235. mit_func->second(GetID(), name, msg, need_ack, ack_resp);*/
  236. }else{
  237. log_info("web-message: not found cmd, MsgFuncList.size()=%d", __MsgFuncList.size());
  238. for(auto it = __MsgFuncList.begin(); it != __MsgFuncList.end(); ++it){
  239. log_info("cmd: %s", it->first.c_str());
  240. }
  241. }
  242. }else{
  243. log_info("web-message: parse error!");
  244. }
  245. }
  246. }
  247. void wsClient::_OnLoginResponse( std::string const & name, sio::message::ptr const & data, bool need_ack, sio::message::list & ack_resp )
  248. {
  249. char szError[512] = { 0 };
  250. int res_code = ( int ) data->get_map()["code"]->get_int();
  251. switch ( res_code )
  252. {
  253. case -1:
  254. {
  255. __Logined = false;
  256. sprintf( szError, "Login failed,code=%d", res_code );
  257. __LastError = szError;
  258. break;
  259. }
  260. case 0:
  261. {
  262. __Logined = true;
  263. break;
  264. }
  265. default:
  266. break;
  267. }
  268. }
  269. int wsClient::GetID()
  270. {
  271. return __ID;
  272. }
  273. bool wsClient::IsConnected()
  274. {
  275. return __Connected;
  276. }
  277. bool wsClient::IsSktOpened()
  278. {
  279. return __SktOpened;
  280. }
  281. bool wsClient::IsLogined()
  282. {
  283. return __Logined;
  284. }
  285. void wsClient::close()
  286. {
  287. __wsclient.sync_close();
  288. // __wsclient.close();
  289. log_info("[wsclient] %d close, reason=%s", __ID, GetLastError().c_str());
  290. }
  291. void wsClient::reconnect()
  292. {
  293. __wsclient.sync_close();
  294. while(!IsConnected()){
  295. try{
  296. if(connect() < 0){
  297. log_info("[wsclient] error=%s", GetLastError().c_str());
  298. std::this_thread::sleep_for(std::chrono::seconds(3));
  299. continue;
  300. }
  301. login();
  302. std::this_thread::sleep_for(std::chrono::seconds(10));
  303. }catch(...)
  304. {
  305. log_info("[wsclient] connect error");
  306. }
  307. }
  308. log_info("[wsClient] %d reconnect successful.", __ID);
  309. }
  310. std::string wsClient::GetLastError()
  311. {
  312. return __LastError;
  313. }
  314. int wsClient::GetPingTime() const
  315. {
  316. return __recv_ping_time;
  317. }
  318. sio::message::ptr wsClient::to_sio_message(const std::string& val)
  319. {
  320. sio::message::ptr message = sio::object_message::create();
  321. rapidjson::Document doc;
  322. doc.Parse(val.c_str());
  323. log_info("[change sio message] val=%s", val.c_str());
  324. for(auto it = doc.MemberBegin(); it != doc.MemberEnd(); ++it){
  325. std::string key = it->name.GetString();
  326. //log_info("[change sio message] name=%s", key.c_str());
  327. if(it->value.IsString()){
  328. static_cast<sio::object_message*>(message.get())->get_map()[key.c_str()] = sio::string_message::create(it->value.GetString());
  329. }else if(it->value.IsObject()){
  330. static_cast<sio::object_message*>(message.get())->get_map()[key.c_str()] = from_json(it->value);
  331. }else if(it->value.IsArray()){
  332. static_cast<sio::object_message*>(message.get())->get_map()[key.c_str()] = from_array(it->value);
  333. }
  334. }
  335. return message;
  336. }
  337. sio::message::ptr wsClient::call_to_sio_message(const std::string& val)
  338. {
  339. sio::message::ptr message = sio::object_message::create();
  340. rapidjson::Document doc;
  341. doc.Parse(val.c_str());
  342. if(doc.HasParseError()){
  343. log_info("[change sio message] rapidjson::Document pares error.");
  344. return message;
  345. }
  346. for(auto it = doc.MemberBegin(); it != doc.MemberEnd(); ++it){
  347. std::string key = it->name.GetString();
  348. //log_info("[change sio message] key=%s", key.c_str());
  349. if(it->value.IsString()){
  350. static_cast<sio::object_message*>(message.get())->get_map()[key.c_str()] = sio::string_message::create(it->value.GetString());
  351. }else if(it->value.IsObject()){
  352. static_cast<sio::object_message*>(message.get())->get_map()[key.c_str()] = from_json(it->value);
  353. }else if(it->value.IsArray()){
  354. static_cast<sio::object_message*>(message.get())->get_map()[key.c_str()] = from_array(it->value);
  355. }
  356. }
  357. return message;
  358. }
  359. sio::message::ptr wsClient::from_json(const rapidjson::Value& val)
  360. {
  361. sio::message::ptr message = sio::object_message::create();
  362. log_info("[change sio message] from_json");
  363. for(auto it = val.MemberBegin(); it != val.MemberEnd(); ++it){
  364. if(it->value.IsInt()){
  365. static_cast<sio::object_message*>(message.get())->get_map()[it->name.GetString()] = sio::int_message::create(it->value.GetInt());
  366. }else if(it->value.IsString()){
  367. static_cast<sio::object_message*>(message.get())->get_map()[it->name.GetString()] = sio::string_message::create(it->value.GetString());
  368. }else if(it->value.IsBool()){
  369. static_cast<sio::object_message*>(message.get())->get_map()[it->name.GetString()] = sio::bool_message::create(it->value.GetBool());
  370. }else if(it->value.IsDouble()){
  371. static_cast<sio::object_message*>(message.get())->get_map()[it->name.GetString()] = sio::double_message::create(it->value.GetDouble());
  372. }else if(it->value.IsArray()){
  373. static_cast<sio::object_message*>(message.get())->get_map()[it->name.GetString()] = from_array(it->value);
  374. }else if(it->value.IsNull()){
  375. static_cast<sio::object_message*>(message.get())->get_map()[it->name.GetString()] = sio::null_message::create();
  376. }else if(it->value.IsObject()){
  377. static_cast<sio::object_message*>(message.get())->get_map()[it->name.GetString()] = from_json(it->value);
  378. }
  379. }
  380. return message;
  381. }
  382. sio::message::ptr wsClient::from_array(const rapidjson::Value& val)
  383. {
  384. sio::message::ptr message = sio::array_message::create();
  385. log_info("[change sio message] from_array: %s", val.GetString());
  386. for(auto it = val.Begin(); it != val.End(); ++it)
  387. {
  388. if(it->IsInt()){
  389. static_cast<sio::array_message*>(message.get())->get_vector().push_back(sio::int_message::create(it->GetInt()));
  390. }else if(it->IsString()){
  391. static_cast<sio::array_message*>(message.get())->get_vector().push_back(sio::string_message::create(it->GetString()));
  392. }else if(it->IsBool()){
  393. static_cast<sio::array_message*>(message.get())->get_vector().push_back(sio::bool_message::create(it->GetBool()));
  394. }else if(it->IsDouble()){
  395. static_cast<sio::array_message*>(message.get())->get_vector().push_back(sio::double_message::create(it->GetDouble()));
  396. }else if(it->IsObject()){
  397. static_cast<sio::array_message*>(message.get())->get_vector().push_back(from_json(*it));
  398. }
  399. }
  400. return message;
  401. }
  402. }