WebSocketManager.js 4.6 KB

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