WebSocketManager.js 5.1 KB

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