websocketclient.h 2.4 KB

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