wsClient.cpp 6.0 KB

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