webSocket.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. export class LiveWS {
  2. /**
  3. * @param {string} url - WebSocket 服务器地址
  4. * @param {number} liveId - 直播间ID
  5. * @param {number} userId - 用户ID
  6. * @param {number} checkInterval - 检查连接状态的时间间隔,单位毫秒
  7. * @param {number} reconnectDelay - 连接断开后重连的延迟,单位毫秒
  8. */
  9. constructor(url, liveId, userId, checkInterval = 5000, reconnectDelay = 3000) {
  10. this.url = url + `?liveId=${liveId}&userId=${userId}`;
  11. this.liveId = liveId;
  12. this.userId = userId;
  13. this.checkInterval = checkInterval;
  14. this.reconnectDelay = reconnectDelay;
  15. this.ws = null;
  16. this.isManualClose = false;
  17. this.connect();
  18. this.startHeartbeat();
  19. }
  20. connect() {
  21. console.log("Connecting to WebSocket:");
  22. this.ws = new WebSocket(this.url);
  23. // 绑定事件
  24. this.ws.onopen = (event) => {
  25. console.log("WebSocket connected:", event);
  26. };
  27. this.ws.onmessage = (event) => {
  28. console.log("Received message:", event.data);
  29. // 根据需要处理消息
  30. };
  31. this.ws.onerror = (error) => {
  32. console.error("WebSocket error:", error);
  33. };
  34. this.ws.onclose = (event) => {
  35. console.warn("WebSocket closed:", event);
  36. // 如果不是主动关闭,则重连
  37. if (!this.isManualClose) {
  38. setTimeout(() => this.reconnect(), this.reconnectDelay);
  39. }
  40. };
  41. }
  42. reconnect() {
  43. console.log("Reconnecting WebSocket...");
  44. this.connect();
  45. }
  46. // 定时检查连接状态
  47. startHeartbeat() {
  48. this.heartbeatTimer = setInterval(() => {
  49. if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
  50. console.warn("WebSocket not open. Attempting to reconnect...");
  51. this.reconnect();
  52. } else {
  53. // 发送信息
  54. this.ws.send(JSON.stringify({'cmd':'heartbeat','msg':'ping', 'liveId': this.liveId, 'userId': this.userId}));
  55. console.log("WebSocket is healthy.");
  56. }
  57. }, this.checkInterval);
  58. }
  59. // 主动关闭 WebSocket 连接,并清除定时任务
  60. close() {
  61. this.isManualClose = true;
  62. if (this.heartbeatTimer) {
  63. clearInterval(this.heartbeatTimer);
  64. }
  65. if (this.ws) {
  66. this.ws.close();
  67. }
  68. }
  69. // 发送消息方法
  70. send(message) {
  71. if (this.ws && this.ws.readyState === WebSocket.OPEN) {
  72. this.ws.send(message);
  73. } else {
  74. console.error("WebSocket is not open. Message not sent.");
  75. }
  76. }
  77. }