WebSocketManager.js 4.2 KB

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