| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990 |
- #ifndef WEBSOCKETCLIENT_H
- #define WEBSOCKETCLIENT_H
- #include <QJsonDocument>
- #include <QJsonObject>
- #include <QObject>
- #include <QTimer>
- #include <QWebSocket>
- #include "widgets/chatView/chat1/chatmessage.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");
-
- // 发送图片消息
- void sendImageMessage(const QString& imagePath, const QString& text = QString());
- // 获取连接状态
- 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
|