WebSocketManager.js 3.8 KB

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