websocketclient.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  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. void WebSocketClient::sendStreamNotification(bool show)
  150. {
  151. if (!m_connected) {
  152. emit errorOccurred("未连接到聊天室,无法发送推流通知");
  153. return;
  154. }
  155. // 使用现有的room类型,在content中添加特殊标识
  156. QJsonObject message;
  157. message["type"] = "room";
  158. message["content"] = show ? "##STREAM_SHOW##" : "##STREAM_HIDE##";
  159. message["roomId"] = m_roomId;
  160. message["time"] = QDateTime::currentDateTime().toUTC().toString(Qt::ISODate);
  161. QJsonDocument doc(message);
  162. qDebug() << doc.toJson(QJsonDocument::Compact);
  163. m_webSocket.sendTextMessage(doc.toJson(QJsonDocument::Compact));
  164. }
  165. bool WebSocketClient::isConnected() const
  166. {
  167. return m_connected;
  168. }
  169. void WebSocketClient::onConnected()
  170. {
  171. m_connected = true;
  172. m_isReconnecting = false;
  173. m_reconnectAttempts = 0; // 连接成功后重置重连计数
  174. m_pingTimer.start();
  175. emit connectionStateChanged(true);
  176. }
  177. void WebSocketClient::onDisconnected()
  178. {
  179. m_connected = false;
  180. m_pingTimer.stop();
  181. emit connectionStateChanged(false);
  182. // 如果启用了自动重连,且当前不在重连过程中,则尝试重连
  183. if (m_autoReconnect && !m_roomId.isEmpty() && !m_isReconnecting) {
  184. qDebug() << "WebSocket断开连接,准备重连...";
  185. // 使用指数退避策略,每次重连间隔时间增加
  186. int reconnectDelay = 1000 * (1 << qMin(m_reconnectAttempts, 5)); // 最大延迟32秒
  187. m_reconnectTimer.start(reconnectDelay);
  188. }
  189. }
  190. void WebSocketClient::onTextMessageReceived(const QString& message)
  191. {
  192. QJsonParseError error;
  193. QJsonDocument doc = QJsonDocument::fromJson(message.toUtf8(), &error);
  194. if (error.error != QJsonParseError::NoError) {
  195. emit errorOccurred("解析消息失败: " + error.errorString());
  196. return;
  197. }
  198. if (doc.isObject()) {
  199. QJsonObject obj = doc.object();
  200. qDebug() << "----------------------------->" << obj;
  201. // 处理心跳响应
  202. if (obj.contains("type") && obj["type"].toString() == "pong") {
  203. return;
  204. }
  205. // 处理聊天消息
  206. ChatMessage chatMessage;
  207. const QString type = obj["type"].toString();
  208. const QString content = obj["content"].toString();
  209. // 处理特殊消息类型
  210. if (type == "ping") {
  211. return;
  212. } else if (type == "room_live_status") {
  213. emit liveStatus(content);
  214. return;
  215. } else if (type == "stats_update") {
  216. emit statsUpdate(obj);
  217. return;
  218. }
  219. // 设置消息类型
  220. if (type == "room") {
  221. // 检查是否为推流通知消息
  222. if (content == "##STREAM_SHOW##") {
  223. emit streamNotification(true);
  224. return;
  225. } else if (content == "##STREAM_HIDE##") {
  226. emit streamNotification(false);
  227. return;
  228. }
  229. chatMessage.type = MessageType::Left;
  230. } else if (type == "system") {
  231. chatMessage.type = MessageType::System;
  232. } else if (type == "private") {
  233. chatMessage.type = MessageType::Right;
  234. }
  235. // 检查是否包含扩展数据(图片等)
  236. if (obj.contains("data") && !obj["data"].isNull()) {
  237. QJsonObject dataObj = obj["data"].toObject();
  238. QString messageType = dataObj["messageType"].toString();
  239. if (messageType == "image") {
  240. // 处理图片消息
  241. QString imageData = dataObj["imageData"].toString();
  242. QString mimeType = dataObj["mimeType"].toString();
  243. QString fileName = dataObj["fileName"].toString();
  244. // 解码Base64图片数据
  245. QByteArray decodedData = QByteArray::fromBase64(imageData.toLatin1());
  246. // 创建临时文件保存图片
  247. QString tempDir = QStandardPaths::writableLocation(QStandardPaths::TempLocation);
  248. QString tempFileName = QString("chat_image_%1_%2").arg(QDateTime::currentMSecsSinceEpoch()).arg(fileName);
  249. QString tempFilePath = QDir(tempDir).absoluteFilePath(tempFileName);
  250. QFile tempFile(tempFilePath);
  251. if (tempFile.open(QIODevice::WriteOnly)) {
  252. tempFile.write(decodedData);
  253. tempFile.close();
  254. // 设置图片消息属性
  255. chatMessage.imagePath = tempFilePath;
  256. chatMessage.contentType = content.isEmpty() ? ContentType::Image : ContentType::Mixed;
  257. // 获取图片尺寸
  258. QImageReader reader(tempFilePath);
  259. if (reader.canRead()) {
  260. chatMessage.imageSize = reader.size();
  261. }
  262. } else {
  263. qDebug() << "Failed to save image to temp file:" << tempFilePath;
  264. return;
  265. }
  266. }
  267. } else {
  268. // 纯文本消息
  269. chatMessage.contentType = ContentType::Text;
  270. }
  271. // 设置消息内容
  272. chatMessage.text = content;
  273. chatMessage.senderName = obj["fromUserName"].toString();
  274. // 设置时间(如果服务器提供)
  275. if (obj.contains("time") && !obj["time"].toString().isEmpty()) {
  276. QDateTime msgTime = QDateTime::fromString(obj["time"].toString(), Qt::ISODate);
  277. if (msgTime.isValid()) {
  278. chatMessage.timestamp = msgTime;
  279. } else {
  280. chatMessage.timestamp = QDateTime::currentDateTime();
  281. }
  282. } else {
  283. chatMessage.timestamp = QDateTime::currentDateTime();
  284. }
  285. // 设置发送者ID(如果服务器提供)
  286. // if (obj.contains("senderId")) {
  287. // chatMessage.senderId = obj["senderId"].toString();
  288. // }
  289. emit messageReceived(chatMessage);
  290. }
  291. }
  292. void WebSocketClient::onError(QAbstractSocket::SocketError error)
  293. {
  294. Q_UNUSED(error);
  295. emit errorOccurred("WebSocket错误: " + m_webSocket.errorString());
  296. // 错误发生时不需要额外处理,因为错误通常会触发disconnected信号,
  297. // 在onDisconnected中已经处理了重连逻辑
  298. }
  299. void WebSocketClient::sendPing()
  300. {
  301. if (m_connected) {
  302. QJsonObject pingMessage;
  303. pingMessage["type"] = "ping";
  304. pingMessage["time"] = QDateTime::currentDateTime().toString(Qt::ISODate);
  305. QJsonDocument doc(pingMessage);
  306. m_webSocket.sendTextMessage(doc.toJson(QJsonDocument::Compact));
  307. }
  308. }
  309. QUrl WebSocketClient::buildWebSocketUrl(const QString& roomId)
  310. {
  311. // 从HTTP URL构建WebSocket URL
  312. QString baseUrl = TC::RequestClient::globalInstance()->baseUrl();
  313. // 将http(s)://替换为ws(s)://
  314. QString wsUrl = baseUrl;
  315. if (wsUrl.startsWith("https://")) {
  316. wsUrl.replace(0, 8, "wss://");
  317. } else if (wsUrl.startsWith("http://")) {
  318. wsUrl.replace(0, 7, "ws://");
  319. }
  320. if (wsUrl.isEmpty()) {
  321. wsUrl = "ws://127.0.0.1:8200";
  322. }
  323. // 构建完整的WebSocket URL
  324. return QUrl(wsUrl + "/api/ws/chat/" + roomId);
  325. }
  326. void WebSocketClient::tryReconnect()
  327. {
  328. // 防止重复进入重连流程
  329. if (m_isReconnecting || !m_autoReconnect || m_roomId.isEmpty() || m_connected) {
  330. return;
  331. }
  332. m_isReconnecting = true;
  333. m_reconnectAttempts++;
  334. if (m_reconnectAttempts <= m_maxReconnectAttempts) {
  335. qDebug() << "尝试重新连接WebSocket,第" << m_reconnectAttempts << "次尝试...";
  336. emit reconnecting(m_reconnectAttempts, m_maxReconnectAttempts);
  337. // 确保WebSocket处于关闭状态
  338. if (m_webSocket.state() != QAbstractSocket::UnconnectedState) {
  339. m_webSocket.abort();
  340. QTimer::singleShot(500, this, &WebSocketClient::doReconnect);
  341. } else {
  342. doReconnect();
  343. }
  344. } else {
  345. qDebug() << "WebSocket重连失败,已达到最大尝试次数";
  346. emit reconnectFailed();
  347. m_autoReconnect = false; // 禁用自动重连
  348. m_isReconnecting = false;
  349. }
  350. }
  351. void WebSocketClient::doReconnect()
  352. {
  353. QUrl url = buildWebSocketUrl(m_roomId);
  354. QNetworkRequest request(url);
  355. const QString token = AppEvent::instance()->jwtToken();
  356. if (!token.isEmpty()) {
  357. request.setRawHeader("Authorization", "Bearer " + token.toUtf8());
  358. }
  359. request.setRawHeader("Machine-Code", AppEvent::instance()->machineCode().toUtf8());
  360. request.setRawHeader("Accept-Language", AppEvent::instance()->locale().toUtf8());
  361. m_webSocket.open(request);
  362. // 添加超时保护,防止连接过程卡死
  363. QTimer::singleShot(10000, this, [this]() {
  364. if (!m_connected && m_isReconnecting) {
  365. qDebug() << "重连超时,中断当前连接尝试";
  366. m_webSocket.abort();
  367. m_isReconnecting = false;
  368. // 继续下一次重连尝试
  369. if (m_autoReconnect && m_reconnectAttempts < m_maxReconnectAttempts) {
  370. int reconnectDelay = 1000 * (1 << qMin(m_reconnectAttempts, 5));
  371. m_reconnectTimer.start(reconnectDelay);
  372. } else if (m_reconnectAttempts >= m_maxReconnectAttempts) {
  373. emit reconnectFailed();
  374. m_autoReconnect = false;
  375. }
  376. }
  377. });
  378. }
  379. void WebSocketClient::setAutoReconnect(bool enable)
  380. {
  381. m_autoReconnect = enable;
  382. }
  383. void WebSocketClient::setMaxReconnectAttempts(int maxAttempts)
  384. {
  385. m_maxReconnectAttempts = maxAttempts;
  386. }