web_connect.cpp 2.4 KB

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