liveWS.js 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  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. let timestamp = new Date().getTime()
  12. let userType = 1
  13. let signature = CryptoJS.HmacSHA256(
  14. CryptoJS.enc.Utf8.parse('' + liveId + userId + userType + timestamp),
  15. CryptoJS.enc.Utf8.parse(timestamp)).toString(CryptoJS.enc.Hex)
  16. this.url = url + `?liveId=${liveId}&userId=${userId}&userType=${userType}&timestamp=${timestamp}&signature=${signature}`;
  17. console.log(this.url)
  18. this.liveId = liveId;
  19. this.userId = userId;
  20. this.checkInterval = checkInterval;
  21. this.reconnectDelay = reconnectDelay;
  22. this.ws = null;
  23. this.reconnectTimer = null;
  24. this.heartbeatTimer = null;
  25. this.isManualClose = false;
  26. this.connect();
  27. this.startHeartbeat();
  28. }
  29. connect() {
  30. // 如果已经有一个连接处于 OPEN 或 CONNECTING 状态,则不再创建新连接
  31. if (this.ws && (this.ws.readyState === WebSocket.OPEN || this.ws.readyState === WebSocket.CONNECTING)) {
  32. return;
  33. }
  34. this.ws = new WebSocket(this.url);
  35. // 绑定事件
  36. this.ws.onopen = (event) => {
  37. // 连接成功后,清除重连计时器
  38. if (this.reconnectTimer) {
  39. clearTimeout(this.reconnectTimer);
  40. this.reconnectTimer = null;
  41. }
  42. };
  43. this.ws.onmessage = (event) => {
  44. this.onmessage(event);
  45. };
  46. this.ws.onerror = (error) => {
  47. };
  48. this.ws.onclose = (event) => {
  49. // 如果不是主动关闭,则重连
  50. if (!this.isManualClose) {
  51. setTimeout(() => this.reconnect(), this.reconnectDelay);
  52. }
  53. };
  54. }
  55. onmessage(event) {}
  56. reconnect() {
  57. this.connect();
  58. }
  59. // 调度重连
  60. scheduleReconnect() {
  61. // 避免多次重连定时器同时存在
  62. if (this.reconnectTimer) return;
  63. this.reconnectTimer = setTimeout(() => {
  64. this.connect();
  65. }, this.reconnectDelay);
  66. }
  67. // 定时检查连接状态
  68. startHeartbeat() {
  69. this.heartbeatTimer = setInterval(() => {
  70. if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
  71. this.scheduleReconnect();
  72. } else {
  73. // 发送信息
  74. this.ws.send(JSON.stringify({'cmd':'heartbeat','msg':'ping', 'liveId': this.liveId, 'userId': this.userId}));
  75. }
  76. }, this.checkInterval);
  77. }
  78. // 主动关闭 WebSocket 连接,并清除定时任务
  79. close() {
  80. this.isManualClose = true;
  81. if (this.heartbeatTimer) {
  82. clearInterval(this.heartbeatTimer);
  83. }
  84. if (this.reconnectTimer) {
  85. clearTimeout(this.reconnectTimer);
  86. }
  87. if (this.ws) {
  88. this.ws.close();
  89. }
  90. }
  91. // 发送消息方法
  92. send(message) {
  93. if (this.ws && this.ws.readyState === WebSocket.OPEN) {
  94. this.ws.send(message);
  95. } else {
  96. console.error("WebSocket is not open. Message not sent.");
  97. }
  98. }
  99. }