wsClient.cpp 6.3 KB

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