wsClient.cpp 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. #include "wsClient.h"
  2. #include "constdef.h"
  3. #include <thread>
  4. #include <chrono>
  5. #include <boost/locale.hpp>
  6. #include"log.h"
  7. namespace YA
  8. {
  9. const int _LOGIN_SLEEP_TIME_ = 500;//登录前的等待时间(单位:毫秒)
  10. const int _OPEN_SOCKET_WAIT_TIME_ = 100;//等待打开socket时间(单位:毫秒)
  11. wsClient::wsClient()
  12. {
  13. __ID = 0;
  14. _reset();
  15. }
  16. wsClient::~wsClient()
  17. {
  18. __wsclient.sync_close();
  19. }
  20. void wsClient::_reset()
  21. {
  22. __Connected = false;
  23. __SktOpened = false;
  24. __Logined = false;
  25. }
  26. static void beatheart(int, std::string const&, sio::message::ptr const&, bool, sio::message::list & )
  27. {
  28. }
  29. void wsClient::init( int ID, const std::string & uri, const std::map<std::string, MSG_HANDLE_FUNC_TYPE>& MsgFuncList )
  30. {
  31. __ID = ID;
  32. __uri = uri;
  33. __MsgFuncList = MsgFuncList;
  34. //MsgFuncList.insert( std::make_pair( "beatheart", &web_connect::_beatheart_callback ) );
  35. __MsgFuncList.insert(std::make_pair("beatheart",&beatheart));
  36. }
  37. std::string wsClient::get_uri()
  38. {
  39. return __uri;
  40. }
  41. int wsClient::connect( int time_out )
  42. {
  43. if ( __uri.empty() )
  44. {
  45. __LastError = "Error, uri is empty.";
  46. return -1;
  47. }
  48. {
  49. __wsclient.set_reconnect_attempts( 0 );
  50. using std::placeholders::_1;
  51. using std::placeholders::_2;
  52. using std::placeholders::_3;
  53. using std::placeholders::_4;
  54. sio::socket::ptr sock = __wsclient.socket();
  55. __recv_ping_time = 0;
  56. __connet_time = 0;
  57. __wsclient.set_open_listener( std::bind( &wsClient::_on_connected, this ) );
  58. __wsclient.set_close_listener( std::bind( &wsClient::_on_close, this, std::placeholders::_1 ) );
  59. __wsclient.set_reconnect_listener( std::bind( &wsClient::_on_reconnect, this, std::placeholders::_1, std::placeholders::_2 ) );
  60. __wsclient.set_fail_listener( std::bind( &wsClient::_on_fail, this ) );
  61. __wsclient.set_socket_open_listener( std::bind( &wsClient::_on_socket_opened, this ) );
  62. sock->on( JSON_CMD_VALUE_CALL, sio::socket::event_listener_aux( std::bind( &wsClient::_OnCallMessage, this, _1, _2, _3, _4 ) ) );
  63. sock->on( "code", sio::socket::event_listener_aux( std::bind( &wsClient::_OnLoginResponse, this, _1, _2, _3, _4 ) ) );
  64. }
  65. __wsclient.connect( __uri );
  66. std::cv_status status = std::cv_status::timeout;
  67. int nRet = -1;
  68. __lock.lock();
  69. if ( !IsConnected() )
  70. {
  71. status = __cond.wait_for( __lock, std::chrono::seconds( time_out ) );
  72. if ( std::cv_status::timeout == status )
  73. {
  74. __LastError = "Failed to connect server.";
  75. nRet = -1;
  76. }
  77. else
  78. {
  79. unsigned int cur_time = time(0);
  80. __connet_time = cur_time;
  81. __recv_ping_time = cur_time;
  82. nRet = 0;
  83. }
  84. }
  85. else
  86. {
  87. nRet = 0;
  88. }
  89. __lock.unlock();
  90. return nRet;
  91. }
  92. void wsClient::login()
  93. {
  94. if ( !IsConnected() )
  95. {
  96. __LastError = "please connect server before login!";
  97. return;
  98. }
  99. //std::cv_status status = std::cv_status::timeout;
  100. __lock.lock();
  101. if ( !IsSktOpened() )
  102. {
  103. // status =
  104. __cond.wait_for( __lock, std::chrono::milliseconds( _OPEN_SOCKET_WAIT_TIME_ ) );
  105. }
  106. __lock.unlock();
  107. if ( !IsSktOpened() )
  108. {
  109. __LastError = "socket is not opened before login!";
  110. return;
  111. }
  112. std::this_thread::sleep_for( std::chrono::milliseconds( _LOGIN_SLEEP_TIME_ ) );
  113. YA::_JS_LOGIN_ Login;
  114. Login.user_name = JSON_VALUE_USERNAME;
  115. Login.user_password = JSON_VALUE_PASSWORD;
  116. std::string strLogin = __jsBuilder.BuildLogin( Login );
  117. strLogin += "\n";
  118. sio::socket::ptr skt_ptr;
  119. skt_ptr = __wsclient.socket();
  120. skt_ptr->emit( JSON_CMD_VALUE_USER, strLogin, [this]( sio::message::list const& msglist )
  121. {
  122. int nRet = 0;
  123. char szError[512] = { 0 };
  124. sio::message::ptr msg_ptr = msglist[0];
  125. nRet = ( int ) msg_ptr->get_map()["code"]->get_int();
  126. if ( 0 == nRet )
  127. {
  128. __Logined = true;
  129. }
  130. else
  131. {
  132. __Logined = false;
  133. sprintf( szError, "Login failed,code=%d", nRet );
  134. __LastError = szError;
  135. }
  136. } );
  137. }
  138. void wsClient::_on_connected()
  139. {
  140. __lock.lock();
  141. __cond.notify_all();
  142. __Connected = true;
  143. __lock.unlock();
  144. }
  145. void wsClient::send( const std::string & Cmd, const std::string & Data )
  146. {
  147. std::lock_guard<std::recursive_mutex> lock( __send_lock );
  148. sio::socket::ptr skt_ptr;
  149. skt_ptr = __wsclient.socket();
  150. skt_ptr->emit( Cmd, Data );
  151. }
  152. void wsClient::_on_close( sio::client::close_reason const & reason )
  153. {
  154. log_info("websocket %d close()",__ID);
  155. _reset();
  156. }
  157. void wsClient::_on_reconnect( unsigned p1, unsigned p2 )
  158. {
  159. log_info("websocket %d reconnect()",__ID);
  160. _reset();
  161. }
  162. void wsClient::_on_fail()
  163. {
  164. _reset();
  165. }
  166. void wsClient::_on_socket_opened()
  167. {
  168. __SktOpened = true;
  169. }
  170. void wsClient::_OnCallMessage( std::string const& name, sio::message::ptr const& data, bool need_ack, sio::message::list &ack_resp )
  171. {
  172. log_info("web-message:%s",data->to_string().c_str());
  173. if ( data->get_flag() == sio::message::flag_object )
  174. {
  175. std::string cmd = data->get_map()[JSON_ROOT_KEY_CMD]->get_string();
  176. std::map<std::string, MSG_HANDLE_FUNC_TYPE>::iterator mit_func;
  177. mit_func = __MsgFuncList.find( cmd );
  178. if ( mit_func != __MsgFuncList.end() )
  179. {
  180. try
  181. {
  182. mit_func->second( GetID(), name, data, need_ack, ack_resp );
  183. }
  184. catch(const std::exception&e)
  185. {
  186. log_error("捕获到异常:%s",e.what());
  187. }
  188. catch(...)
  189. {
  190. log_error("捕获到未知异常");
  191. }
  192. }
  193. else
  194. {
  195. log_error("web-message没有找到对应的处理函数:%s",data->to_string().c_str());
  196. }
  197. __recv_ping_time = time(0);
  198. }
  199. }
  200. void wsClient::_OnLoginResponse( std::string const & name, sio::message::ptr const & data, bool need_ack, sio::message::list & ack_resp )
  201. {
  202. char szError[512] = { 0 };
  203. int res_code = ( int ) data->get_map()["code"]->get_int();
  204. switch ( res_code )
  205. {
  206. case -1:
  207. {
  208. __Logined = false;
  209. sprintf( szError, "Login failed,code=%d", res_code );
  210. __LastError = szError;
  211. break;
  212. }
  213. case 0:
  214. {
  215. __Logined = true;
  216. break;
  217. }
  218. default:
  219. break;
  220. }
  221. }
  222. int wsClient::GetID()
  223. {
  224. return __ID;
  225. }
  226. bool wsClient::IsConnected()
  227. {
  228. return __Connected;
  229. }
  230. bool wsClient::IsSktOpened()
  231. {
  232. return __SktOpened;
  233. }
  234. bool wsClient::IsLogined()
  235. {
  236. return __Logined;
  237. }
  238. void wsClient::close()
  239. {
  240. __wsclient.sync_close();
  241. // __wsclient.close();
  242. }
  243. std::string wsClient::GetLastError()
  244. {
  245. return __LastError;
  246. }
  247. int wsClient::GetPingTime() const
  248. {
  249. return __recv_ping_time;
  250. }
  251. }