vue3 结合sockjs-client、stompjs 实现websocket长连接
·
后端写了个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>
更多推荐



所有评论(0)