后端写了个ws类型的接口,前端实现长连接。

<script name="" setup>
import SockJS from "sockjs-client/dist/sockjs";
import Stomp from "stompjs";
import {
  onMounted,
  onBeforeUnmount,
  reactive,
  ref,
  computed,
  watch,
} from "vue";
let stompClient = null; // 定义 Stomp 客户端
let reconnectAttempts = 0; // 记录重连次数
let heartbeatInterval = null; // 心跳定时器


/**初始化 websocket**/
const initData = () => {
  // 初始化 WebSocket
  const connectWebSocket = () => {
    const socket = new SockJS("http://192.168.1.1:8081/ws");
    stompClient = Stomp.over(socket);
    stompClient.debug = () => {}; //禁用调试日志

    // 连接成功后的处理
    stompClient.connect(
      {},
      (frame) => {
        console.log("WebSocket 连接成功!");
        reconnectAttempts = 0;
        startHeartbeat();
        stompClient.subscribe("/topic/diskSpace", (message) => {
          console.log("清理报警", JSON.parse(message.body));
          
        });
      },
      (error) => {
        console.error("WebSocket 连接失败:", error);
        attemptReconnect(); // 尝试重连
      }
    );

    // 监听连接关闭事件
    socket.onclose = () => {
      console.warn("WebSocket 连接关闭");
      stopHeartbeat(); // 停止心跳
      attemptReconnect(); // 尝试重连
    };
  };

  // 尝试重连
  const attemptReconnect = () => {
    if (reconnectAttempts < 10) {
      const delay = Math.min(1000 * 2 ** reconnectAttempts, 30000); // 指数退避,最大 30 秒
      console.log(`尝试重新连接,延迟: ${delay}ms`);
      reconnectAttempts += 1;

      setTimeout(() => {
        connectWebSocket(); // 重连
      }, delay);
    } else {
      console.error("多次重连失败,请检查服务器或网络状态。");
    }
  };

  // 启动心跳机制
  const startHeartbeat = () => {
    if (heartbeatInterval) {
      clearInterval(heartbeatInterval);
    }
    heartbeatInterval = setInterval(() => {
      if (stompClient && stompClient.connected) {
        stompClient.send(
          "/app/heartbeat",
          {},
          JSON.stringify({ type: "ping" })
        );
        //console.log("发送心跳包");
      } else {
        console.warn("心跳发送失败,WebSocket 未连接");
      }
    }, 5000); // 每 5 秒发送一次心跳
  };

  // 初始连接
  connectWebSocket();
};

// 停止心跳
const stopHeartbeat = () => {
  if (heartbeatInterval) {
    clearInterval(heartbeatInterval);
    heartbeatInterval = null;
  }
};

onMounted(() => {
  initData();
});
onBeforeUnmount(() => {
  if (data.ws) {
    data.ws.close();
  }
});
</script>
Logo

中国智能体开发者社区,聚焦智能体与大模型开发,提供前沿资讯、实用工具链、开源项目及行业案例。通过技术沙龙、开发者大赛等活动,促进经验交流与协作,助力开发者快速构建创新智能应用。

更多推荐