websocketclient.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #ifndef WEBSOCKETCLIENT_H
  2. #define WEBSOCKETCLIENT_H
  3. #include <QJsonDocument>
  4. #include <QJsonObject>
  5. #include <QObject>
  6. #include <QTimer>
  7. #include <QWebSocket>
  8. #include "widgets/chatView/chat1/chatmessage.h"
  9. class WebSocketClient : public QObject
  10. {
  11. Q_OBJECT
  12. public:
  13. explicit WebSocketClient(QObject *parent = nullptr);
  14. ~WebSocketClient();
  15. // 连接到聊天室
  16. void connectToRoom(const QString& roomId);
  17. // 断开连接
  18. void disconnect();
  19. // 发送消息
  20. void sendMessage(const QString& content, const QString& type = "room");
  21. // 发送图片消息
  22. void sendImageMessage(const QString& imagePath, const QString& text = QString());
  23. // 获取连接状态
  24. bool isConnected() const;
  25. // 设置是否自动重连
  26. void setAutoReconnect(bool enable);
  27. // 设置最大重连尝试次数
  28. void setMaxReconnectAttempts(int maxAttempts);
  29. QString roomId() const { return m_roomId; }
  30. signals:
  31. // 收到新消息信号
  32. void messageReceived(const ChatMessage& message);
  33. // 直播状态
  34. void liveStatus(const QString& message);
  35. // 统计信息更新
  36. void statsUpdate(const QJsonObject& statsData);
  37. // 连接状态变化信号
  38. void connectionStateChanged(bool connected);
  39. // 错误信号
  40. void errorOccurred(const QString& errorMessage);
  41. // 正在尝试重连的信号
  42. void reconnecting(int attempt, int maxAttempts);
  43. // 重连失败的信号
  44. void reconnectFailed();
  45. private slots:
  46. void onConnected();
  47. void onDisconnected();
  48. void onTextMessageReceived(const QString& message);
  49. void onError(QAbstractSocket::SocketError error);
  50. void sendPing();
  51. // 尝试重新连接
  52. void tryReconnect();
  53. // 执行实际的重连操作
  54. void doReconnect();
  55. private:
  56. QWebSocket m_webSocket;
  57. QString m_roomId;
  58. QTimer m_pingTimer;
  59. bool m_connected;
  60. bool m_autoReconnect; // 是否自动重连
  61. int m_reconnectAttempts; // 当前重连尝试次数
  62. int m_maxReconnectAttempts; // 最大重连尝试次数
  63. QTimer m_reconnectTimer; // 重连定时器
  64. bool m_isReconnecting; // 是否正在重连中
  65. // 构建WebSocket URL
  66. QUrl buildWebSocketUrl(const QString& roomId);
  67. };
  68. #endif // WEBSOCKETCLIENT_H