wsClient.cpp 6.6 KB

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