| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586 |
- #ifndef WEBSOCKETCLIENT_H
- #define WEBSOCKETCLIENT_H
- #include <QJsonDocument>
- #include <QJsonObject>
- #include <QObject>
- #include <QTimer>
- #include <QWebSocket>
- #include "models/chatmodels.h"
- class WebSocketClient : public QObject
- {
- Q_OBJECT
- public:
- explicit WebSocketClient(QObject *parent = nullptr);
- ~WebSocketClient();
- // 连接到聊天室
- void connectToRoom(const QString& roomId);
-
- // 断开连接
- void disconnect();
-
- // 发送消息
- void sendMessage(const QString& content, const QString& type = "room");
- // 获取连接状态
- bool isConnected() const;
- // 设置是否自动重连
- void setAutoReconnect(bool enable);
-
- // 设置最大重连尝试次数
- void setMaxReconnectAttempts(int maxAttempts);
- QString roomId() const { return m_roomId; }
- signals:
- // 收到新消息信号
- void messageReceived(const ChatMessage& message);
- // 直播状态
- void liveStatus(const QString& message);
- // 统计信息更新
- void statsUpdate(const QJsonObject& statsData);
- // 连接状态变化信号
- void connectionStateChanged(bool connected);
-
- // 错误信号
- void errorOccurred(const QString& errorMessage);
- // 正在尝试重连的信号
- void reconnecting(int attempt, int maxAttempts);
-
- // 重连失败的信号
- void reconnectFailed();
- private slots:
- void onConnected();
- void onDisconnected();
- void onTextMessageReceived(const QString& message);
- void onError(QAbstractSocket::SocketError error);
- void sendPing();
-
- // 尝试重新连接
- void tryReconnect();
-
- // 执行实际的重连操作
- void doReconnect();
- private:
- QWebSocket m_webSocket;
- QString m_roomId;
- QTimer m_pingTimer;
- bool m_connected;
- bool m_autoReconnect; // 是否自动重连
- int m_reconnectAttempts; // 当前重连尝试次数
- int m_maxReconnectAttempts; // 最大重连尝试次数
- QTimer m_reconnectTimer; // 重连定时器
- bool m_isReconnecting; // 是否正在重连中
-
- // 构建WebSocket URL
- QUrl buildWebSocketUrl(const QString& roomId);
- };
- #endif // WEBSOCKETCLIENT_H
|