websocketclient.h 2.0 KB

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