WebSocketManager.js 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  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. this.isConnecting = true;
  35. console.log('建立 WebSocket 连接:', this.url);
  36. this.socketTask = uni.connectSocket({
  37. url: this.url,
  38. success: (res) => console.log('WebSocket 连接创建成功',res),
  39. header: {
  40. 'Authorization': `Bearer ${getToken()}`
  41. },
  42. });
  43. this._setupEventListeners();
  44. }
  45. /**
  46. * 设置事件监听器
  47. */
  48. _setupEventListeners() {
  49. this.socketTask.onOpen(() => {
  50. console.log('WebSocket 已打开');
  51. this.isConnecting = false;
  52. this.startHeartbeat();
  53. });
  54. this.socketTask.onMessage(res => {
  55. console.log('收到 WebSocket 消息:', res.data);
  56. try {
  57. const data = JSON.parse(res.data);
  58. // console.log("TCL: WebSocketManager -> _setupEventListeners -> data", data)
  59. if (typeof this.onMessageCallback === 'function') {
  60. this.onMessageCallback(data); // 回调通知外部
  61. }
  62. if (data.type === 'msgUnreadCount') {
  63. console.log("TCL: WebSocketManager -> _setupEventListeners -> msgUnreadCount", data.data)
  64. store.dispatch('handleMessageCount', data.data)
  65. }
  66. } catch (e) {
  67. console.error('消息解析失败:', res.data);
  68. }
  69. });
  70. this.socketTask.onError(err => {
  71. console.error('WebSocket 发生错误:', err);
  72. this.connectCount <= 3 && this.reconnect();
  73. });
  74. this.socketTask.onClose(() => {
  75. console.log('WebSocket 已关闭',this.connectCount);
  76. this.stopHeartbeat();
  77. // this.connectCount <= 3 && this.reconnect();
  78. });
  79. }
  80. /**
  81. * 启动心跳机制
  82. */
  83. startHeartbeat() {
  84. // this.stopHeartbeat();
  85. // this.heartbeatInterval = setInterval(() => {
  86. // uni.sendSocketMessage({
  87. // data: 'heartbeat',
  88. // success: () => console.log('心跳包已发送'),
  89. // fail: err => {
  90. // console.error('心跳包发送失败:', err);
  91. // this.stopHeartbeat();
  92. // }
  93. // });
  94. // }, 5000);
  95. }
  96. /**
  97. * 停止心跳机制
  98. */
  99. stopHeartbeat() {
  100. if (this.heartbeatInterval) {
  101. clearInterval(this.heartbeatInterval);
  102. this.heartbeatInterval = null;
  103. }
  104. }
  105. /**
  106. * 重新连接
  107. */
  108. reconnect() {
  109. console.log('尝试重新连接...');
  110. this.connectCount = this.connectCount +1;
  111. this.connect();
  112. }
  113. /**
  114. * 主动发送消息
  115. */
  116. sendMessage(message) {
  117. if (this.socketTask && typeof message !== 'undefined') {
  118. uni.sendSocketMessage({
  119. data: typeof message === 'object' ? JSON.stringify(message) : message,
  120. success: () => console.log('消息发送成功:', message),
  121. fail: err => console.error('消息发送失败:', err)
  122. });
  123. } else {
  124. console.warn('尚未建立连接,消息发送失败');
  125. }
  126. }
  127. /**
  128. * 主动关闭连接
  129. */
  130. closeConnection() {
  131. console.log('主动关闭连接',this.socketTask,this.isConnected);
  132. uni.closeSocket(this.socketTask);
  133. this.socketTask.close();
  134. this.socketTask = null;
  135. this.stopHeartbeat();
  136. store.dispatch('handleSoket', null)
  137. }
  138. /**
  139. * 设置消息回调
  140. */
  141. onMessage(callback) {
  142. // console.log("TCL: WebSocketManager -> onMessage -> callback", callback)
  143. this.onMessageCallback = callback;
  144. }
  145. }
  146. export default WebSocketManager;