WebSocketManager.js 3.9 KB

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