websocketclient.cpp 8.9 KB

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