WebSocketService.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. export default class WebSocketService {
  2. constructor(url) {
  3. this.socket = null;
  4. this.url = url;
  5. // 心跳定时器
  6. this.heartbeatTimer = null;
  7. this.heartbeatInterval = 30000; // 30秒
  8. // 重连次数
  9. this.reconnectAttempts = 50; // 默认重连次数
  10. this.maxReconnectAttempts = 100; // 最大重连次数
  11. this.reconnectInterval = 2000; // 2秒
  12. // 存储回调函数
  13. this.onMessageCallback = null; // 存储回调函数
  14. }
  15. // 重连
  16. reconnect() {
  17. if (this.reconnectAttempts < this.maxReconnectAttempts) {
  18. this.reconnectAttempts++;
  19. console.log(`尝试重新连接... (${this.reconnectAttempts}/${this.maxReconnectAttempts})`);
  20. setTimeout(() => {
  21. this.connect();
  22. }, this.reconnectInterval);
  23. } else {
  24. console.error('达到最大重连次数,连接失败');
  25. }
  26. }
  27. // 开启心跳
  28. startHeartbeat() {
  29. this.heartbeatTimer = setInterval(() => {
  30. this.send({ type: 'heartbeat' });
  31. }, this.heartbeatInterval);
  32. }
  33. // 关闭心跳
  34. stopHeartbeat() {
  35. if (this.heartbeatTimer) {
  36. clearInterval(this.heartbeatTimer);
  37. this.heartbeatTimer = null;
  38. }
  39. }
  40. // 连接
  41. async connect() {
  42. this.socket = new WebSocket(this.url);
  43. this.socket.onopen = await this.onOpen.bind(this);
  44. this.socket.onmessage = this.onMessage.bind(this);
  45. this.socket.onclose = this.onClose.bind(this);
  46. this.socket.onerror = this.onError.bind(this);
  47. }
  48. // 连接成功
  49. onOpen() {
  50. console.log('WebSocket连接已建立');
  51. this.reconnectAttempts = 0;
  52. this.startHeartbeat();
  53. }
  54. //
  55. onMessage(event) {
  56. console.log('收到消息:', event.data);
  57. if (this.onMessageCallback) {
  58. this.onMessageCallback(event.data); // 调用回调函数
  59. }
  60. }
  61. // 接收到错误消息
  62. onClose() {
  63. console.log('WebSocket连接已关闭');
  64. this.stopHeartbeat();
  65. this.reconnect();
  66. }
  67. // 接收到错误消息
  68. onError(error) {
  69. console.error('WebSocket错误:', error);
  70. }
  71. // 发送消息
  72. send(data) {
  73. if (this.socket && this.socket.readyState === WebSocket.OPEN) {
  74. this.socket.send(JSON.stringify(data));
  75. } else {
  76. console.error('WebSocket未连接');
  77. }
  78. }
  79. // 关闭连接
  80. close() {
  81. if (this.socket) {
  82. this.socket.close();
  83. }
  84. }
  85. }
  86. // urls: [
  87. // 'turn:124.71.68.142:3478?transport=udp', // 强制UDP
  88. // 'turn:124.71.68.142:3478?transport=tcp' // TCP备用
  89. // ]
  90. // const ws = new WebSocketService(`ws://192.168.0.59:3001/ws?user_id=${userId}`)