liveWS.js 3.1 KB

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