QThreadHttpClient.h 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #pragma once
  2. #include <QObject>
  3. #include <QTimer> // 添加定时器头文件
  4. #include "httplib.h"
  5. #include <QMutex>
  6. #include <QWaitCondition> // 添加等待条件
  7. #include "platform.h"
  8. #include "NetMessageDefine.h"
  9. class QThreadHttpClient : public QObject
  10. {
  11. Q_OBJECT
  12. public:
  13. // 获取单例实例
  14. static QThreadHttpClient& instance();
  15. // 清空所有数据
  16. static void destroyInstance();
  17. void initHttpClient();
  18. bool HttpPost(const std::string& strUrl, const std::string& strRequest, std::string& strResponse);
  19. bool reconnect(); // 添加重连方法
  20. bool isConnected();
  21. bool reconnectNoLock();
  22. // 获取连接状态
  23. bool getReconnectStatus() const { return m_bReconnectSuccess; }
  24. //初始化
  25. void InitConnect(QObject* pCMD);
  26. // 等待连接(用于主线程阻塞等待)
  27. bool waitForConnection(int timeoutMs = 30000);
  28. signals:
  29. void signal_SignalData(std::string strUrl, std::string strRequest);
  30. //void signal_ConnectionStatusChanged(bool connected); // 连接状态变化信号
  31. //void signal_ReconnectAttempt(int attemptCount, bool success); // 重连尝试信号
  32. public slots:
  33. void slot_CMDPop(int nCmdID, OCCCOMMAND pCmdData);
  34. void slot_SendPost(std::string strUrl, std::string strRequest);
  35. void slot_ReconnectTimer(); // 定时重连槽函数
  36. private:
  37. QThreadHttpClient(QObject* parent);
  38. ~QThreadHttpClient();
  39. void AddLogJson(std::string strRequest, std::string strResponse, std::string nAPIID, bool bStatus);
  40. void startReconnectTimer(); // 启动重连定时器
  41. void stopReconnectTimer(); // 停止重连定时器
  42. // 禁止拷贝和赋值
  43. QThreadHttpClient(const QThreadHttpClient&) = delete;
  44. QThreadHttpClient& operator=(const QThreadHttpClient&) = delete;
  45. static QThreadHttpClient* g_HttpSingle;
  46. static QMutex m_clientMutex; // 改为 QMutex
  47. private:
  48. httplib::Client* pClient;
  49. QTimer* m_reconnectTimer; // 重连定时器
  50. bool m_bReconnectSuccess; // 重连成功标志
  51. int m_reconnectAttemptCount; // 重连尝试次数
  52. int m_maxReconnectAttempts; // 最大重连尝试次数
  53. QWaitCondition m_connectionCondition; // 连接等待条件
  54. QMutex m_connectionMutex; // 连接状态互斥锁
  55. };