WebSocketManager.js 3.9 KB

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