web_connect.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. #include "web_connect.h"
  2. #include<thread>
  3. #include<chrono>
  4. #include"log.h"
  5. #include"wsClientMgr.h"
  6. #include"wsTimerThread.h"
  7. #define BEATHEART_COUNT_NUM 1000
  8. web_connect::web_connect()
  9. {
  10. }
  11. std::atomic<int> web_connect::_beatheart_count;
  12. void web_connect::init(const std::vector<std::string>&uri_list,int32_t st, std::map<std::string, YA::MSG_HANDLE_FUNC_TYPE>& MsgFuncList)
  13. {
  14. MsgFuncList.insert( std::make_pair( "beatheart", &web_connect::_beatheart_callback ) );
  15. swsClientMgr.Build( uri_list, MsgFuncList );
  16. //init thread...
  17. YA::_THREAD_CONFIG_ Config;
  18. Config.SendInterval = st;
  19. swsTimerThrd.Init( Config );
  20. }
  21. void web_connect::start_beatheart_monitor()
  22. {
  23. auto th = std::thread(&web_connect::_beatheart_thread);
  24. th.detach();
  25. }
  26. void web_connect::close()
  27. {
  28. swsTimerThrd.Stop();
  29. swsClientMgr.close();
  30. }
  31. bool web_connect::connect()
  32. {
  33. //连接服务器
  34. if ( swsClientMgr.connect() != 0 )
  35. {
  36. log_error("web socket 连接失败....");
  37. std_error("websocket 连接失败....");
  38. return false;
  39. }
  40. //登录
  41. swsClientMgr.login();
  42. swsTimerThrd.Start();
  43. return true;
  44. }
  45. void web_connect::_beatheart_callback( int ID, std::string const& name,
  46. sio::message::ptr const& data, bool need_ack, sio::message::list &ack_resp )
  47. {
  48. _beatheart_count=BEATHEART_COUNT_NUM;
  49. }
  50. void web_connect::_beatheart_thread()
  51. {
  52. while (true)
  53. {
  54. std::this_thread::sleep_for(std::chrono::seconds(3));
  55. if(_beatheart_count==0)//一次都没收到web的心跳信号
  56. {
  57. log_info("没有收到web心跳信号");
  58. continue;
  59. }
  60. if(_beatheart_count==BEATHEART_COUNT_NUM)
  61. {
  62. _beatheart_count++;
  63. log_info("接收到web心跳信号");
  64. continue;
  65. }
  66. _beatheart_count=0;
  67. int count=0;
  68. while (true)
  69. {
  70. count++;
  71. if(count>=10000)
  72. {
  73. count=10000;
  74. }
  75. close();
  76. log_error("web连接异常中断, 开始重连web(第%d次)", count);
  77. std::this_thread::sleep_for(std::chrono::seconds(2));
  78. if(connect())
  79. {
  80. log_info("重连web ok");
  81. break;
  82. }
  83. }
  84. }
  85. }