WebSocketManager.js 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  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. if (typeof this.onMessageCallback === 'function') {
  52. this.onMessageCallback(data); // 回调通知外部
  53. }
  54. } catch (e) {
  55. console.error('消息解析失败:', res.data);
  56. }
  57. });
  58. this.socketTask.onError(err => {
  59. console.error('WebSocket 发生错误:', err);
  60. });
  61. this.socketTask.onClose(() => {
  62. console.log('WebSocket 已关闭');
  63. this.stopHeartbeat();
  64. this.reconnect(); // 自动重连
  65. });
  66. }
  67. /**
  68. * 启动心跳机制
  69. */
  70. startHeartbeat() {
  71. // this.stopHeartbeat();
  72. // this.heartbeatInterval = setInterval(() => {
  73. // uni.sendSocketMessage({
  74. // data: 'heartbeat',
  75. // success: () => console.log('心跳包已发送'),
  76. // fail: err => {
  77. // console.error('心跳包发送失败:', err);
  78. // this.stopHeartbeat();
  79. // }
  80. // });
  81. // }, 5000);
  82. }
  83. /**
  84. * 停止心跳机制
  85. */
  86. stopHeartbeat() {
  87. if (this.heartbeatInterval) {
  88. clearInterval(this.heartbeatInterval);
  89. this.heartbeatInterval = null;
  90. }
  91. }
  92. /**
  93. * 重新连接
  94. */
  95. reconnect() {
  96. clearTimeout(this.reconnectTimer);
  97. this.reconnectTimer = setTimeout(() => {
  98. console.log('尝试重新连接...');
  99. this.connect();
  100. }, 3000);
  101. }
  102. /**
  103. * 主动发送消息
  104. */
  105. sendMessage(message) {
  106. if (this.socketTask && typeof message !== 'undefined') {
  107. uni.sendSocketMessage({
  108. data: typeof message === 'object' ? JSON.stringify(message) : message,
  109. success: () => console.log('消息发送成功:', message),
  110. fail: err => console.error('消息发送失败:', err)
  111. });
  112. } else {
  113. console.warn('尚未建立连接,消息发送失败');
  114. }
  115. }
  116. /**
  117. * 主动关闭连接
  118. */
  119. closeConnection() {
  120. console.log('主动关闭连接',this.socketTask);
  121. this.socketTask.close();
  122. this.socketTask = null;
  123. // this.stopHeartbeat();
  124. }
  125. /**
  126. * 设置消息回调
  127. */
  128. onMessage(callback) {
  129. this.onMessageCallback = callback;
  130. }
  131. }
  132. export default WebSocketManager;