websocketclient.h 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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 "models/chatmodels.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. bool isConnected() const;
  23. // 设置是否自动重连
  24. void setAutoReconnect(bool enable);
  25. // 设置最大重连尝试次数
  26. void setMaxReconnectAttempts(int maxAttempts);
  27. QString roomId() const { return m_roomId; }
  28. signals:
  29. // 收到新消息信号
  30. void messageReceived(const ChatMessage& message);
  31. // 直播状态
  32. void liveStatus(const QString& message);
  33. // 统计信息更新
  34. void statsUpdate(const QJsonObject& statsData);
  35. // 连接状态变化信号
  36. void connectionStateChanged(bool connected);
  37. // 错误信号
  38. void errorOccurred(const QString& errorMessage);
  39. // 正在尝试重连的信号
  40. void reconnecting(int attempt, int maxAttempts);
  41. // 重连失败的信号
  42. void reconnectFailed();
  43. private slots:
  44. void onConnected();
  45. void onDisconnected();
  46. void onTextMessageReceived(const QString& message);
  47. void onError(QAbstractSocket::SocketError error);
  48. void sendPing();
  49. // 尝试重新连接
  50. void tryReconnect();
  51. // 执行实际的重连操作
  52. void doReconnect();
  53. private:
  54. QWebSocket m_webSocket;
  55. QString m_roomId;
  56. QTimer m_pingTimer;
  57. bool m_connected;
  58. bool m_autoReconnect; // 是否自动重连
  59. int m_reconnectAttempts; // 当前重连尝试次数
  60. int m_maxReconnectAttempts; // 最大重连尝试次数
  61. QTimer m_reconnectTimer; // 重连定时器
  62. bool m_isReconnecting; // 是否正在重连中
  63. // 构建WebSocket URL
  64. QUrl buildWebSocketUrl(const QString& roomId);
  65. };
  66. #endif // WEBSOCKETCLIENT_H