websocketclient.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. #include "websocketclient.h"
  2. #include <QJsonDocument>
  3. #include <QJsonObject>
  4. #include <QJsonParseError>
  5. #include <QUrl>
  6. #include <QUrlQuery>
  7. #include <QFileInfo>
  8. #include <QBuffer>
  9. #include <QImageReader>
  10. #include <QStandardPaths>
  11. #include <QDir>
  12. #include <QFile>
  13. #include "networkaccessmanager.h"
  14. #include <appevent.h>
  15. WebSocketClient::WebSocketClient(QObject* parent)
  16. : QObject(parent)
  17. , m_connected(false)
  18. , m_autoReconnect(true)
  19. , m_reconnectAttempts(0)
  20. , m_maxReconnectAttempts(300)
  21. , m_isReconnecting(false)
  22. {
  23. // 连接WebSocket信号
  24. connect(&m_webSocket, &QWebSocket::connected, this, &WebSocketClient::onConnected);
  25. connect(&m_webSocket, &QWebSocket::disconnected, this, &WebSocketClient::onDisconnected);
  26. connect(&m_webSocket,
  27. &QWebSocket::textMessageReceived,
  28. this,
  29. &WebSocketClient::onTextMessageReceived);
  30. connect(&m_webSocket,
  31. QOverload<QAbstractSocket::SocketError>::of(&QWebSocket::error),
  32. this,
  33. &WebSocketClient::onError);
  34. // 设置心跳包定时器
  35. connect(&m_pingTimer, &QTimer::timeout, this, &WebSocketClient::sendPing);
  36. m_pingTimer.setInterval(30000); // 30秒发送一次心跳
  37. // 设置重连定时器
  38. m_reconnectTimer.setSingleShot(true);
  39. connect(&m_reconnectTimer, &QTimer::timeout, this, &WebSocketClient::tryReconnect);
  40. }
  41. WebSocketClient::~WebSocketClient()
  42. {
  43. disconnect();
  44. }
  45. void WebSocketClient::connectToRoom(const QString& roomId)
  46. {
  47. if (m_connected) {
  48. disconnect();
  49. }
  50. m_roomId = roomId;
  51. m_reconnectAttempts = 0; // 重置重连尝试次数
  52. QUrl url = buildWebSocketUrl(roomId);
  53. qDebug() << "connectToRoom" << url;
  54. // 设置请求头
  55. QNetworkRequest request(url);
  56. const QString token = AppEvent::instance()->jwtToken();
  57. if (!token.isEmpty()) {
  58. request.setRawHeader("Authorization", "Bearer " + token.toUtf8());
  59. }
  60. qDebug() << "---" << token;
  61. request.setRawHeader("Machine-Code", AppEvent::instance()->machineCode().toUtf8());
  62. request.setRawHeader("Accept-Language", AppEvent::instance()->locale().toUtf8());
  63. // 连接WebSocket
  64. m_webSocket.open(request);
  65. }
  66. void WebSocketClient::disconnect()
  67. {
  68. m_autoReconnect = false; // 禁用自动重连
  69. m_reconnectTimer.stop(); // 停止重连定时器
  70. if (m_connected) {
  71. m_pingTimer.stop();
  72. m_webSocket.close();
  73. m_connected = false;
  74. emit connectionStateChanged(false);
  75. }
  76. }
  77. void WebSocketClient::sendMessage(const QString& content, const QString& type)
  78. {
  79. if (!m_connected) {
  80. emit errorOccurred("未连接到聊天室,无法发送消息");
  81. return;
  82. }
  83. QJsonObject message;
  84. message["content"] = content;
  85. message["type"] = type;
  86. message["roomId"] = m_roomId;
  87. message["time"] = QDateTime::currentDateTime().toUTC().toString(Qt::ISODate);
  88. QJsonDocument doc(message);
  89. m_webSocket.sendTextMessage(doc.toJson(QJsonDocument::Compact));
  90. }
  91. void WebSocketClient::sendImageMessage(const QString& imagePath, const QString& text)
  92. {
  93. if (!m_connected) {
  94. emit errorOccurred("未连接到聊天室,无法发送图片消息");
  95. return;
  96. }
  97. // 检查文件是否存在
  98. QFileInfo fileInfo(imagePath);
  99. if (!fileInfo.exists() || !fileInfo.isFile()) {
  100. emit errorOccurred("图片文件不存在: " + imagePath);
  101. return;
  102. }
  103. // 读取图片文件并转换为Base64
  104. QFile file(imagePath);
  105. if (!file.open(QIODevice::ReadOnly)) {
  106. emit errorOccurred("无法读取图片文件: " + imagePath);
  107. return;
  108. }
  109. QByteArray imageData = file.readAll();
  110. file.close();
  111. // 检查文件大小限制(例如5MB)
  112. const qint64 maxFileSize = 5 * 1024 * 1024; // 5MB
  113. if (imageData.size() > maxFileSize) {
  114. emit errorOccurred("图片文件过大,请选择小于5MB的图片");
  115. return;
  116. }
  117. // 获取文件扩展名来确定MIME类型
  118. QString mimeType = "image/jpeg"; // 默认
  119. QString suffix = fileInfo.suffix().toLower();
  120. if (suffix == "png") {
  121. mimeType = "image/png";
  122. } else if (suffix == "gif") {
  123. mimeType = "image/gif";
  124. } else if (suffix == "bmp") {
  125. mimeType = "image/bmp";
  126. } else if (suffix == "webp") {
  127. mimeType = "image/webp";
  128. }
  129. // 构建符合WSMessage结构的消息
  130. QJsonObject message;
  131. message["type"] = "room"; // 使用room类型
  132. message["roomId"] = m_roomId;
  133. message["time"] = QDateTime::currentDateTime().toUTC().toString(Qt::ISODate);
  134. // 如果有附加文本消息,放在content字段
  135. if (!text.isEmpty()) {
  136. message["content"] = text;
  137. }
  138. // 图片数据放在data字段中
  139. QJsonObject imageData_obj;
  140. imageData_obj["messageType"] = "image"; // 标识这是图片消息
  141. imageData_obj["imageData"] = QString::fromLatin1(imageData.toBase64());
  142. imageData_obj["mimeType"] = mimeType;
  143. imageData_obj["fileName"] = fileInfo.fileName();
  144. imageData_obj["fileSize"] = imageData.size();
  145. message["data"] = imageData_obj;
  146. QJsonDocument doc(message);
  147. m_webSocket.sendTextMessage(doc.toJson(QJsonDocument::Compact));
  148. }
  149. bool WebSocketClient::isConnected() const
  150. {
  151. return m_connected;
  152. }
  153. void WebSocketClient::onConnected()
  154. {
  155. m_connected = true;
  156. m_isReconnecting = false;
  157. m_reconnectAttempts = 0; // 连接成功后重置重连计数
  158. m_pingTimer.start();
  159. emit connectionStateChanged(true);
  160. }
  161. void WebSocketClient::onDisconnected()
  162. {
  163. m_connected = false;
  164. m_pingTimer.stop();
  165. emit connectionStateChanged(false);
  166. // 如果启用了自动重连,且当前不在重连过程中,则尝试重连
  167. if (m_autoReconnect && !m_roomId.isEmpty() && !m_isReconnecting) {
  168. qDebug() << "WebSocket断开连接,准备重连...";
  169. // 使用指数退避策略,每次重连间隔时间增加
  170. int reconnectDelay = 1000 * (1 << qMin(m_reconnectAttempts, 5)); // 最大延迟32秒
  171. m_reconnectTimer.start(reconnectDelay);
  172. }
  173. }
  174. void WebSocketClient::onTextMessageReceived(const QString& message)
  175. {
  176. QJsonParseError error;
  177. QJsonDocument doc = QJsonDocument::fromJson(message.toUtf8(), &error);
  178. if (error.error != QJsonParseError::NoError) {
  179. emit errorOccurred("解析消息失败: " + error.errorString());
  180. return;
  181. }
  182. if (doc.isObject()) {
  183. QJsonObject obj = doc.object();
  184. qDebug() << "----------------------------->" << obj;
  185. // 处理心跳响应
  186. if (obj.contains("type") && obj["type"].toString() == "pong") {
  187. return;
  188. }
  189. // 处理聊天消息
  190. ChatMessage chatMessage;
  191. const QString type = obj["type"].toString();
  192. const QString content = obj["content"].toString();
  193. // 处理特殊消息类型
  194. if (type == "ping") {
  195. return;
  196. } else if (type == "room_live_status") {
  197. emit liveStatus(content);
  198. return;
  199. } else if (type == "stats_update") {
  200. emit statsUpdate(obj);
  201. return;
  202. }
  203. // 设置消息类型
  204. if (type == "room") {
  205. chatMessage.type = MessageType::Left;
  206. } else if (type == "system") {
  207. chatMessage.type = MessageType::System;
  208. } else if (type == "private") {
  209. chatMessage.type = MessageType::Right;
  210. }
  211. // 检查是否包含扩展数据(图片等)
  212. if (obj.contains("data") && !obj["data"].isNull()) {
  213. QJsonObject dataObj = obj["data"].toObject();
  214. QString messageType = dataObj["messageType"].toString();
  215. if (messageType == "image") {
  216. // 处理图片消息
  217. QString imageData = dataObj["imageData"].toString();
  218. QString mimeType = dataObj["mimeType"].toString();
  219. QString fileName = dataObj["fileName"].toString();
  220. // 解码Base64图片数据
  221. QByteArray decodedData = QByteArray::fromBase64(imageData.toLatin1());
  222. // 创建临时文件保存图片
  223. QString tempDir = QStandardPaths::writableLocation(QStandardPaths::TempLocation);
  224. QString tempFileName = QString("chat_image_%1_%2").arg(QDateTime::currentMSecsSinceEpoch()).arg(fileName);
  225. QString tempFilePath = QDir(tempDir).absoluteFilePath(tempFileName);
  226. QFile tempFile(tempFilePath);
  227. if (tempFile.open(QIODevice::WriteOnly)) {
  228. tempFile.write(decodedData);
  229. tempFile.close();
  230. // 设置图片消息属性
  231. chatMessage.imagePath = tempFilePath;
  232. chatMessage.contentType = content.isEmpty() ? ContentType::Image : ContentType::Mixed;
  233. // 获取图片尺寸
  234. QImageReader reader(tempFilePath);
  235. if (reader.canRead()) {
  236. chatMessage.imageSize = reader.size();
  237. }
  238. } else {
  239. qDebug() << "Failed to save image to temp file:" << tempFilePath;
  240. return;
  241. }
  242. }
  243. } else {
  244. // 纯文本消息
  245. chatMessage.contentType = ContentType::Text;
  246. }
  247. // 设置消息内容
  248. chatMessage.text = content;
  249. chatMessage.senderName = obj["fromUserName"].toString();
  250. // 设置时间(如果服务器提供)
  251. if (obj.contains("time") && !obj["time"].toString().isEmpty()) {
  252. QDateTime msgTime = QDateTime::fromString(obj["time"].toString(), Qt::ISODate);
  253. if (msgTime.isValid()) {
  254. chatMessage.timestamp = msgTime;
  255. } else {
  256. chatMessage.timestamp = QDateTime::currentDateTime();
  257. }
  258. } else {
  259. chatMessage.timestamp = QDateTime::currentDateTime();
  260. }
  261. // 设置发送者ID(如果服务器提供)
  262. // if (obj.contains("senderId")) {
  263. // chatMessage.senderId = obj["senderId"].toString();
  264. // }
  265. emit messageReceived(chatMessage);
  266. }
  267. }
  268. void WebSocketClient::onError(QAbstractSocket::SocketError error)
  269. {
  270. Q_UNUSED(error);
  271. emit errorOccurred("WebSocket错误: " + m_webSocket.errorString());
  272. // 错误发生时不需要额外处理,因为错误通常会触发disconnected信号,
  273. // 在onDisconnected中已经处理了重连逻辑
  274. }
  275. void WebSocketClient::sendPing()
  276. {
  277. if (m_connected) {
  278. QJsonObject pingMessage;
  279. pingMessage["type"] = "ping";
  280. pingMessage["time"] = QDateTime::currentDateTime().toString(Qt::ISODate);
  281. QJsonDocument doc(pingMessage);
  282. m_webSocket.sendTextMessage(doc.toJson(QJsonDocument::Compact));
  283. }
  284. }
  285. QUrl WebSocketClient::buildWebSocketUrl(const QString& roomId)
  286. {
  287. // 从HTTP URL构建WebSocket URL
  288. QString baseUrl = TC::RequestClient::globalInstance()->baseUrl();
  289. // 将http(s)://替换为ws(s)://
  290. QString wsUrl = baseUrl;
  291. if (wsUrl.startsWith("https://")) {
  292. wsUrl.replace(0, 8, "wss://");
  293. } else if (wsUrl.startsWith("http://")) {
  294. wsUrl.replace(0, 7, "ws://");
  295. }
  296. if (wsUrl.isEmpty()) {
  297. wsUrl = "ws://127.0.0.1:8200";
  298. }
  299. // 构建完整的WebSocket URL
  300. return QUrl(wsUrl + "/api/ws/chat/" + roomId);
  301. }
  302. void WebSocketClient::tryReconnect()
  303. {
  304. // 防止重复进入重连流程
  305. if (m_isReconnecting || !m_autoReconnect || m_roomId.isEmpty() || m_connected) {
  306. return;
  307. }
  308. m_isReconnecting = true;
  309. m_reconnectAttempts++;
  310. if (m_reconnectAttempts <= m_maxReconnectAttempts) {
  311. qDebug() << "尝试重新连接WebSocket,第" << m_reconnectAttempts << "次尝试...";
  312. emit reconnecting(m_reconnectAttempts, m_maxReconnectAttempts);
  313. // 确保WebSocket处于关闭状态
  314. if (m_webSocket.state() != QAbstractSocket::UnconnectedState) {
  315. m_webSocket.abort();
  316. QTimer::singleShot(500, this, &WebSocketClient::doReconnect);
  317. } else {
  318. doReconnect();
  319. }
  320. } else {
  321. qDebug() << "WebSocket重连失败,已达到最大尝试次数";
  322. emit reconnectFailed();
  323. m_autoReconnect = false; // 禁用自动重连
  324. m_isReconnecting = false;
  325. }
  326. }
  327. void WebSocketClient::doReconnect()
  328. {
  329. QUrl url = buildWebSocketUrl(m_roomId);
  330. QNetworkRequest request(url);
  331. const QString token = AppEvent::instance()->jwtToken();
  332. if (!token.isEmpty()) {
  333. request.setRawHeader("Authorization", "Bearer " + token.toUtf8());
  334. }
  335. request.setRawHeader("Machine-Code", AppEvent::instance()->machineCode().toUtf8());
  336. request.setRawHeader("Accept-Language", AppEvent::instance()->locale().toUtf8());
  337. m_webSocket.open(request);
  338. // 添加超时保护,防止连接过程卡死
  339. QTimer::singleShot(10000, this, [this]() {
  340. if (!m_connected && m_isReconnecting) {
  341. qDebug() << "重连超时,中断当前连接尝试";
  342. m_webSocket.abort();
  343. m_isReconnecting = false;
  344. // 继续下一次重连尝试
  345. if (m_autoReconnect && m_reconnectAttempts < m_maxReconnectAttempts) {
  346. int reconnectDelay = 1000 * (1 << qMin(m_reconnectAttempts, 5));
  347. m_reconnectTimer.start(reconnectDelay);
  348. } else if (m_reconnectAttempts >= m_maxReconnectAttempts) {
  349. emit reconnectFailed();
  350. m_autoReconnect = false;
  351. }
  352. }
  353. });
  354. }
  355. void WebSocketClient::setAutoReconnect(bool enable)
  356. {
  357. m_autoReconnect = enable;
  358. }
  359. void WebSocketClient::setMaxReconnectAttempts(int maxAttempts)
  360. {
  361. m_maxReconnectAttempts = maxAttempts;
  362. }