websocketclient.cpp 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. #include "websocketclient.h"
  2. #include <QJsonDocument>
  3. #include <QJsonObject>
  4. #include <QJsonParseError>
  5. #include <QUrl>
  6. #include <QUrlQuery>
  7. #include "networkaccessmanager.h"
  8. #include <appevent.h>
  9. WebSocketClient::WebSocketClient(QObject* parent)
  10. : QObject(parent)
  11. , m_connected(false)
  12. , m_autoReconnect(true)
  13. , m_reconnectAttempts(0)
  14. , m_maxReconnectAttempts(300)
  15. , m_isReconnecting(false)
  16. {
  17. // 连接WebSocket信号
  18. connect(&m_webSocket, &QWebSocket::connected, this, &WebSocketClient::onConnected);
  19. connect(&m_webSocket, &QWebSocket::disconnected, this, &WebSocketClient::onDisconnected);
  20. connect(&m_webSocket,
  21. &QWebSocket::textMessageReceived,
  22. this,
  23. &WebSocketClient::onTextMessageReceived);
  24. connect(&m_webSocket,
  25. QOverload<QAbstractSocket::SocketError>::of(&QWebSocket::error),
  26. this,
  27. &WebSocketClient::onError);
  28. // 设置心跳包定时器
  29. connect(&m_pingTimer, &QTimer::timeout, this, &WebSocketClient::sendPing);
  30. m_pingTimer.setInterval(30000); // 30秒发送一次心跳
  31. // 设置重连定时器
  32. m_reconnectTimer.setSingleShot(true);
  33. connect(&m_reconnectTimer, &QTimer::timeout, this, &WebSocketClient::tryReconnect);
  34. }
  35. WebSocketClient::~WebSocketClient()
  36. {
  37. disconnect();
  38. }
  39. void WebSocketClient::connectToRoom(const QString& roomId)
  40. {
  41. if (m_connected) {
  42. disconnect();
  43. }
  44. m_roomId = roomId;
  45. m_reconnectAttempts = 0; // 重置重连尝试次数
  46. QUrl url = buildWebSocketUrl(roomId);
  47. qDebug() << "connectToRoom" << url;
  48. // 设置请求头
  49. QNetworkRequest request(url);
  50. const QString token = AppEvent::instance()->jwtToken();
  51. if (!token.isEmpty()) {
  52. request.setRawHeader("Authorization", "Bearer " + token.toUtf8());
  53. }
  54. qDebug() << "---" << token;
  55. request.setRawHeader("Machine-Code", AppEvent::instance()->machineCode().toUtf8());
  56. request.setRawHeader("Accept-Language", AppEvent::instance()->locale().toUtf8());
  57. // 连接WebSocket
  58. m_webSocket.open(request);
  59. }
  60. void WebSocketClient::disconnect()
  61. {
  62. m_autoReconnect = false; // 禁用自动重连
  63. m_reconnectTimer.stop(); // 停止重连定时器
  64. if (m_connected) {
  65. m_pingTimer.stop();
  66. m_webSocket.close();
  67. m_connected = false;
  68. emit connectionStateChanged(false);
  69. }
  70. }
  71. void WebSocketClient::sendMessage(const QString& content, const QString& type)
  72. {
  73. if (!m_connected) {
  74. emit errorOccurred("未连接到聊天室,无法发送消息");
  75. return;
  76. }
  77. QJsonObject message;
  78. message["content"] = content;
  79. message["type"] = type;
  80. message["roomId"] = m_roomId;
  81. message["time"] = QDateTime::currentDateTime().toUTC().toString(Qt::ISODate);
  82. QJsonDocument doc(message);
  83. m_webSocket.sendTextMessage(doc.toJson(QJsonDocument::Compact));
  84. }
  85. bool WebSocketClient::isConnected() const
  86. {
  87. return m_connected;
  88. }
  89. void WebSocketClient::onConnected()
  90. {
  91. m_connected = true;
  92. m_isReconnecting = false;
  93. m_reconnectAttempts = 0; // 连接成功后重置重连计数
  94. m_pingTimer.start();
  95. emit connectionStateChanged(true);
  96. }
  97. void WebSocketClient::onDisconnected()
  98. {
  99. m_connected = false;
  100. m_pingTimer.stop();
  101. emit connectionStateChanged(false);
  102. // 如果启用了自动重连,且当前不在重连过程中,则尝试重连
  103. if (m_autoReconnect && !m_roomId.isEmpty() && !m_isReconnecting) {
  104. qDebug() << "WebSocket断开连接,准备重连...";
  105. // 使用指数退避策略,每次重连间隔时间增加
  106. int reconnectDelay = 1000 * (1 << qMin(m_reconnectAttempts, 5)); // 最大延迟32秒
  107. m_reconnectTimer.start(reconnectDelay);
  108. }
  109. }
  110. void WebSocketClient::onTextMessageReceived(const QString& message)
  111. {
  112. QJsonParseError error;
  113. QJsonDocument doc = QJsonDocument::fromJson(message.toUtf8(), &error);
  114. if (error.error != QJsonParseError::NoError) {
  115. emit errorOccurred("解析消息失败: " + error.errorString());
  116. return;
  117. }
  118. if (doc.isObject()) {
  119. QJsonObject obj = doc.object();
  120. // 处理心跳响应
  121. if (obj.contains("type") && obj["type"].toString() == "pong") {
  122. return;
  123. }
  124. // 处理聊天消息
  125. ChatMessage chatMessage;
  126. const QString type = obj["type"].toString();
  127. const QString content = obj["content"].toString();
  128. // 设置消息类型
  129. if (type == "room") {
  130. chatMessage.type = MessageType::Left;
  131. } else if (type == "system") {
  132. chatMessage.type = MessageType::System;
  133. } else if (type == "private") {
  134. chatMessage.type = MessageType::Right;
  135. }
  136. // 设置消息内容
  137. chatMessage.text = content;
  138. // 设置时间(如果服务器提供)
  139. if (obj.contains("time") && !obj["time"].toString().isEmpty()) {
  140. QDateTime msgTime = QDateTime::fromString(obj["time"].toString(), Qt::ISODate);
  141. if (msgTime.isValid()) {
  142. chatMessage.timestamp = msgTime;
  143. } else {
  144. chatMessage.timestamp = QDateTime::currentDateTime();
  145. }
  146. } else {
  147. chatMessage.timestamp = QDateTime::currentDateTime();
  148. }
  149. // 设置发送者ID(如果服务器提供)
  150. // if (obj.contains("senderId")) {
  151. // chatMessage.senderId = obj["senderId"].toString();
  152. // }
  153. emit messageReceived(chatMessage);
  154. }
  155. }
  156. void WebSocketClient::onError(QAbstractSocket::SocketError error)
  157. {
  158. Q_UNUSED(error);
  159. emit errorOccurred("WebSocket错误: " + m_webSocket.errorString());
  160. // 错误发生时不需要额外处理,因为错误通常会触发disconnected信号,
  161. // 在onDisconnected中已经处理了重连逻辑
  162. }
  163. void WebSocketClient::sendPing()
  164. {
  165. if (m_connected) {
  166. QJsonObject pingMessage;
  167. pingMessage["type"] = "ping";
  168. pingMessage["time"] = QDateTime::currentDateTime().toString(Qt::ISODate);
  169. QJsonDocument doc(pingMessage);
  170. m_webSocket.sendTextMessage(doc.toJson(QJsonDocument::Compact));
  171. }
  172. }
  173. QUrl WebSocketClient::buildWebSocketUrl(const QString& roomId)
  174. {
  175. // 从HTTP URL构建WebSocket URL
  176. QString baseUrl = TC::RequestClient::requestClient()->baseUrl();
  177. // 将http(s)://替换为ws(s)://
  178. QString wsUrl = baseUrl;
  179. if (wsUrl.startsWith("https://")) {
  180. wsUrl.replace(0, 8, "wss://");
  181. } else if (wsUrl.startsWith("http://")) {
  182. wsUrl.replace(0, 7, "ws://");
  183. }
  184. if (wsUrl.isEmpty()) {
  185. wsUrl = "ws://127.0.0.1:8200";
  186. }
  187. // 构建完整的WebSocket URL
  188. return QUrl(wsUrl + "/api/ws/chat/" + roomId);
  189. }
  190. void WebSocketClient::tryReconnect()
  191. {
  192. // 防止重复进入重连流程
  193. if (m_isReconnecting || !m_autoReconnect || m_roomId.isEmpty() || m_connected) {
  194. return;
  195. }
  196. m_isReconnecting = true;
  197. m_reconnectAttempts++;
  198. if (m_reconnectAttempts <= m_maxReconnectAttempts) {
  199. qDebug() << "尝试重新连接WebSocket,第" << m_reconnectAttempts << "次尝试...";
  200. emit reconnecting(m_reconnectAttempts, m_maxReconnectAttempts);
  201. // 确保WebSocket处于关闭状态
  202. if (m_webSocket.state() != QAbstractSocket::UnconnectedState) {
  203. m_webSocket.abort();
  204. QTimer::singleShot(500, this, &WebSocketClient::doReconnect);
  205. } else {
  206. doReconnect();
  207. }
  208. } else {
  209. qDebug() << "WebSocket重连失败,已达到最大尝试次数";
  210. emit reconnectFailed();
  211. m_autoReconnect = false; // 禁用自动重连
  212. m_isReconnecting = false;
  213. }
  214. }
  215. void WebSocketClient::doReconnect()
  216. {
  217. QUrl url = buildWebSocketUrl(m_roomId);
  218. QNetworkRequest request(url);
  219. const QString token = AppEvent::instance()->jwtToken();
  220. if (!token.isEmpty()) {
  221. request.setRawHeader("Authorization", "Bearer " + token.toUtf8());
  222. }
  223. request.setRawHeader("Machine-Code", AppEvent::instance()->machineCode().toUtf8());
  224. request.setRawHeader("Accept-Language", AppEvent::instance()->locale().toUtf8());
  225. m_webSocket.open(request);
  226. // 添加超时保护,防止连接过程卡死
  227. QTimer::singleShot(10000, this, [this]() {
  228. if (!m_connected && m_isReconnecting) {
  229. qDebug() << "重连超时,中断当前连接尝试";
  230. m_webSocket.abort();
  231. m_isReconnecting = false;
  232. // 继续下一次重连尝试
  233. if (m_autoReconnect && m_reconnectAttempts < m_maxReconnectAttempts) {
  234. int reconnectDelay = 1000 * (1 << qMin(m_reconnectAttempts, 5));
  235. m_reconnectTimer.start(reconnectDelay);
  236. } else if (m_reconnectAttempts >= m_maxReconnectAttempts) {
  237. emit reconnectFailed();
  238. m_autoReconnect = false;
  239. }
  240. }
  241. });
  242. }
  243. void WebSocketClient::setAutoReconnect(bool enable)
  244. {
  245. m_autoReconnect = enable;
  246. }
  247. void WebSocketClient::setMaxReconnectAttempts(int maxAttempts)
  248. {
  249. m_maxReconnectAttempts = maxAttempts;
  250. }