liveWS.js 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. import CryptoJS from 'crypto-js'
  2. export class LiveWS {
  3. /**
  4. * @param {string} url - WebSocket 服务器地址
  5. * @param {number} liveId - 直播间ID
  6. * @param {number} userId - 用户ID
  7. * @param {number} checkInterval - 检查连接状态的时间间隔,单位毫秒
  8. * @param {number} reconnectDelay - 连接断开后重连的延迟,单位毫秒
  9. */
  10. constructor(url, liveId, userId, checkInterval = 5000, reconnectDelay = 3000) {
  11. // 【V-06 修复】HMAC 密钥改为服务端固定 secret(与 live.ws.admin-secret 一致)
  12. let timestamp = new Date().getTime()
  13. let userType = 1
  14. const adminSecret = process.env.VUE_APP_LIVE_WS_ADMIN_SECRET || 'live-ws-admin-hmac-v1'
  15. let signature = CryptoJS.HmacSHA256(
  16. CryptoJS.enc.Utf8.parse('' + liveId + userId + userType + timestamp),
  17. CryptoJS.enc.Utf8.parse(adminSecret)).toString(CryptoJS.enc.Hex)
  18. this.url = url + `?liveId=${liveId}&userId=${userId}&userType=${userType}&timestamp=${timestamp}&signature=${signature}`;
  19. this.liveId = liveId;
  20. this.userId = userId;
  21. this.checkInterval = checkInterval;
  22. this.reconnectDelay = reconnectDelay;
  23. this.ws = null;
  24. this.reconnectTimer = null;
  25. this.heartbeatTimer = null;
  26. this.isManualClose = false;
  27. this.connect();
  28. this.startHeartbeat();
  29. }
  30. connect() {
  31. // 如果已经有一个连接处于 OPEN 或 CONNECTING 状态,则不再创建新连接
  32. if (this.ws && (this.ws.readyState === WebSocket.OPEN || this.ws.readyState === WebSocket.CONNECTING)) {
  33. return;
  34. }
  35. this.ws = new WebSocket(this.url);
  36. // 绑定事件
  37. this.ws.onopen = (event) => {
  38. // 连接成功后,清除重连计时器
  39. if (this.reconnectTimer) {
  40. clearTimeout(this.reconnectTimer);
  41. this.reconnectTimer = null;
  42. }
  43. };
  44. this.ws.onmessage = (event) => {
  45. this.onmessage(event);
  46. };
  47. this.ws.onerror = (error) => {
  48. };
  49. this.ws.onclose = (event) => {
  50. // 如果不是主动关闭,则重连
  51. if (!this.isManualClose) {
  52. setTimeout(() => this.reconnect(), this.reconnectDelay);
  53. }
  54. };
  55. }
  56. onmessage(event) {}
  57. reconnect() {
  58. this.connect();
  59. }
  60. // 调度重连
  61. scheduleReconnect() {
  62. // 避免多次重连定时器同时存在
  63. if (this.reconnectTimer) return;
  64. this.reconnectTimer = setTimeout(() => {
  65. this.connect();
  66. }, this.reconnectDelay);
  67. }
  68. // 定时检查连接状态
  69. startHeartbeat() {
  70. this.heartbeatTimer = setInterval(() => {
  71. if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
  72. this.scheduleReconnect();
  73. } else {
  74. // 发送信息
  75. this.ws.send(JSON.stringify({'cmd':'heartbeat','msg':'ping', 'liveId': this.liveId, 'userId': this.userId}));
  76. }
  77. }, this.checkInterval);
  78. }
  79. // 主动关闭 WebSocket 连接,并清除定时任务
  80. close() {
  81. this.isManualClose = true;
  82. if (this.heartbeatTimer) {
  83. clearInterval(this.heartbeatTimer);
  84. }
  85. if (this.reconnectTimer) {
  86. clearTimeout(this.reconnectTimer);
  87. }
  88. if (this.ws) {
  89. this.ws.close();
  90. }
  91. }
  92. // 发送消息方法
  93. send(message) {
  94. if (this.ws && this.ws.readyState === WebSocket.OPEN) {
  95. this.ws.send(message);
  96. } else {
  97. console.error("WebSocket is not open. Message not sent.");
  98. }
  99. }
  100. }