websocketclient.cpp 15 KB

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