WebSocketManager.js 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. import config from '@/config'
  2. const baseUrl = config.baseUrl
  3. class WebSocketManager {
  4. constructor(userId) {
  5. // 1用户 2志愿者
  6. this.system = uni.getStorageSync('userType') === 1 ? '1' : '2';
  7. this.userId = userId;
  8. const url = baseUrl.split('/')[2];
  9. const header = baseUrl.split('/')[0] === 'https:' ? 'wss' : 'ws';
  10. console.log("TCL: WebSocketManager -> constructor -> url",header, url)
  11. this.url = `${header}://${url}/websocket/${this.system}/${this.userId}`;
  12. this.socketTask = null;
  13. this.heartbeatInterval = null;
  14. this.reconnectTimer = null;
  15. this.isConnecting = false;
  16. this.onMessageCallback = null;
  17. }
  18. /**
  19. * 建立连接
  20. */
  21. connect() {
  22. if (this.isConnecting || !this.userId) {
  23. console.warn('正在连接或缺少用户ID');
  24. return;
  25. }
  26. // 如果已有连接,先关闭旧连接
  27. if (this.isConnected) {
  28. console.log('已存在连接,正在关闭旧连接...');
  29. this.socketTask.close();
  30. }
  31. this.isConnecting = true;
  32. console.log('建立 WebSocket 连接:', this.url);
  33. this.socketTask = uni.connectSocket({
  34. url: this.url,
  35. success: () => console.log('WebSocket 连接创建成功'),
  36. });
  37. this._setupEventListeners();
  38. }
  39. /**
  40. * 设置事件监听器
  41. */
  42. _setupEventListeners() {
  43. this.socketTask.onOpen(() => {
  44. console.log('WebSocket 已打开');
  45. this.isConnecting = false;
  46. this.startHeartbeat();
  47. });
  48. this.socketTask.onMessage(res => {
  49. console.log('收到 WebSocket 消息:', res.data);
  50. try {
  51. const data = JSON.parse(res.data);
  52. console.log("TCL: WebSocketManager -> _setupEventListeners -> data", data)
  53. if (typeof this.onMessageCallback === 'function') {
  54. this.onMessageCallback(data); // 回调通知外部
  55. }
  56. } catch (e) {
  57. console.error('消息解析失败:', res.data);
  58. }
  59. });
  60. this.socketTask.onError(err => {
  61. console.error('WebSocket 发生错误:', err);
  62. });
  63. this.socketTask.onClose(() => {
  64. console.log('WebSocket 已关闭');
  65. this.stopHeartbeat();
  66. this.reconnect(); // 自动重连
  67. });
  68. }
  69. /**
  70. * 启动心跳机制
  71. */
  72. startHeartbeat() {
  73. // this.stopHeartbeat();
  74. // this.heartbeatInterval = setInterval(() => {
  75. // uni.sendSocketMessage({
  76. // data: 'heartbeat',
  77. // success: () => console.log('心跳包已发送'),
  78. // fail: err => {
  79. // console.error('心跳包发送失败:', err);
  80. // this.stopHeartbeat();
  81. // }
  82. // });
  83. // }, 5000);
  84. }
  85. /**
  86. * 停止心跳机制
  87. */
  88. stopHeartbeat() {
  89. if (this.heartbeatInterval) {
  90. clearInterval(this.heartbeatInterval);
  91. this.heartbeatInterval = null;
  92. }
  93. }
  94. /**
  95. * 重新连接
  96. */
  97. reconnect() {
  98. clearTimeout(this.reconnectTimer);
  99. this.reconnectTimer = setTimeout(() => {
  100. console.log('尝试重新连接...');
  101. this.connect();
  102. }, 3000);
  103. }
  104. /**
  105. * 主动发送消息
  106. */
  107. sendMessage(message) {
  108. if (this.socketTask && typeof message !== 'undefined') {
  109. uni.sendSocketMessage({
  110. data: typeof message === 'object' ? JSON.stringify(message) : message,
  111. success: () => console.log('消息发送成功:', message),
  112. fail: err => console.error('消息发送失败:', err)
  113. });
  114. } else {
  115. console.warn('尚未建立连接,消息发送失败');
  116. }
  117. }
  118. /**
  119. * 主动关闭连接
  120. */
  121. closeConnection() {
  122. console.log('主动关闭连接',this.socketTask);
  123. this.socketTask.close();
  124. this.socketTask = null;
  125. // this.stopHeartbeat();
  126. }
  127. /**
  128. * 设置消息回调
  129. */
  130. onMessage(callback) {
  131. console.log("TCL: WebSocketManager -> onMessage -> callback", callback)
  132. this.onMessageCallback = callback;
  133. }
  134. }
  135. export default WebSocketManager;