useWebSocket.js 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. import { onBeforeUnmount, reactive, ref } from 'vue';
  2. import { baseUrl, websocketPath } from '@/sheep/config';
  3. import { copyValueToTarget } from '@/sheep/util';
  4. import { getRefreshToken } from '@/sheep/request';
  5. /**
  6. * WebSocket 创建 hook
  7. * @param opt 连接配置
  8. * @return {{options: *}}
  9. */
  10. export function useWebSocket(opt) {
  11. const options = reactive({
  12. url: (baseUrl + websocketPath).replace('http', 'ws') + '?token=' + getRefreshToken(), // ws 地址
  13. isReconnecting: false, // 正在重新连接
  14. reconnectInterval: 3000, // 重连间隔,单位毫秒
  15. heartBeatInterval: 5000, // 心跳间隔,单位毫秒
  16. pingTimeoutDuration: 1000, // 超过这个时间,后端没有返回pong,则判定后端断线了。
  17. heartBeatTimer: null, // 心跳计时器
  18. destroy: false, // 是否销毁
  19. pingTimeout: null, // 心跳检测定时器
  20. reconnectTimeout: null, // 重连定时器ID的属性
  21. onConnected: () => {}, // 连接成功时触发
  22. onClosed: () => {}, // 连接关闭时触发
  23. onMessage: (data) => {}, // 收到消息
  24. });
  25. const SocketTask = ref(null); // SocketTask 由 uni.connectSocket() 接口创建
  26. const initEventListeners = () => {
  27. // 监听 WebSocket 连接打开事件
  28. SocketTask.value.onOpen(() => {
  29. console.log('WebSocket 连接成功');
  30. // 连接成功时触发
  31. options.onConnected();
  32. // 开启心跳检查
  33. startHeartBeat();
  34. });
  35. // 监听 WebSocket 接受到服务器的消息事件
  36. SocketTask.value.onMessage((res) => {
  37. try {
  38. if (res.data === 'pong') {
  39. // 收到心跳重置心跳超时检查
  40. resetPingTimeout();
  41. } else {
  42. options.onMessage(JSON.parse(res.data));
  43. }
  44. } catch (error) {
  45. console.error(error);
  46. }
  47. });
  48. // 监听 WebSocket 连接关闭事件
  49. SocketTask.value.onClose((event) => {
  50. // 情况一:实例销毁
  51. if (options.destroy) {
  52. options.onClosed();
  53. } else {
  54. // 情况二:连接失败重连
  55. // 停止心跳检查
  56. stopHeartBeat();
  57. // 重连
  58. reconnect();
  59. }
  60. });
  61. };
  62. // 发送消息
  63. const sendMessage = (message) => {
  64. if (SocketTask.value && !options.destroy) {
  65. SocketTask.value.send({ data: message });
  66. }
  67. };
  68. // 开始心跳检查
  69. const startHeartBeat = () => {
  70. options.heartBeatTimer = setInterval(() => {
  71. sendMessage('ping');
  72. options.pingTimeout = setTimeout(() => {
  73. // 如果在超时时间内没有收到 pong,则认为连接断开
  74. reconnect();
  75. }, options.pingTimeoutDuration);
  76. }, options.heartBeatInterval);
  77. };
  78. // 停止心跳检查
  79. const stopHeartBeat = () => {
  80. clearInterval(options.heartBeatTimer);
  81. resetPingTimeout();
  82. };
  83. // WebSocket 重连
  84. const reconnect = () => {
  85. if (options.destroy || !SocketTask.value) {
  86. // 如果WebSocket已被销毁或尚未完全关闭,不进行重连
  87. return;
  88. }
  89. // 重连中
  90. options.isReconnecting = true;
  91. // 清除现有的重连标志,以避免多次重连
  92. if (options.reconnectTimeout) {
  93. clearTimeout(options.reconnectTimeout);
  94. }
  95. // 设置重连延迟
  96. options.reconnectTimeout = setTimeout(() => {
  97. // 检查组件是否仍在运行和WebSocket是否关闭
  98. if (!options.destroy) {
  99. // 重置重连标志
  100. options.isReconnecting = false;
  101. // 初始化新的WebSocket连接
  102. initSocket();
  103. }
  104. }, options.reconnectInterval);
  105. };
  106. const resetPingTimeout = () => {
  107. if (options.pingTimeout) {
  108. clearTimeout(options.pingTimeout);
  109. options.pingTimeout = null; // 清除超时ID
  110. }
  111. };
  112. const close = () => {
  113. options.destroy = true;
  114. stopHeartBeat();
  115. if (options.reconnectTimeout) {
  116. clearTimeout(options.reconnectTimeout);
  117. }
  118. if (SocketTask.value) {
  119. SocketTask.value.close();
  120. SocketTask.value = null;
  121. }
  122. };
  123. const initSocket = () => {
  124. options.destroy = false;
  125. copyValueToTarget(options, opt);
  126. SocketTask.value = uni.connectSocket({
  127. url: options.url,
  128. complete: () => {},
  129. success: () => {},
  130. });
  131. initEventListeners();
  132. };
  133. initSocket();
  134. onBeforeUnmount(() => {
  135. close();
  136. });
  137. return { options };
  138. }