阅读量:0
直接上代码,如果有帮助,希望不要白嫖,点赞+收藏!
generateUniqueRandomKey 方法,具体参考上一篇文章 ,csdn链接: https://blog.csdn.net/weixin_44180579/article/details/140708809
// useWebSocket.ts // useWebSocket.js import { ref, onMounted, onBeforeUnmount } from "vue"; import { generateUniqueRandomKey } from "@/utils/utils"; //具体参考上一篇文章 export default function useWebSocket( url: string, onMessageCallback: any, onErrorCallback = (error: any) => {} ) { // 状态管理 const socketRef = ref(null); const isConnected = ref(false); const reconnectAttempts = ref(0); // 最大重连次数 const maxReconnectAttempts = 5; // 重连间隔时间,单位毫秒 const reconnectInterval = 2000; //每次进页面,生成唯一标识符 const uniqueKey = generateUniqueRandomKey(12); // 初始化WebSocket连接 const initWebSocket = () => { // 拼接12位唯一标识符 let newUrl = url + "/" + uniqueKey; socketRef.value = new WebSocket(newUrl); socketRef.value.onopen = () => { isConnected.value = true; console.log("----------websocket连接成功----------"); reconnectAttempts.value = 0; // 成功连接后重置重连尝试次数 }; socketRef.value.onerror = (error: any) => { onErrorCallback(error); }; socketRef.value.onclose = (event: any) => { isConnected.value = false; //断线重连 if (reconnectAttempts.value < maxReconnectAttempts) { setTimeout(initWebSocket, reconnectInterval); reconnectAttempts.value++; } else { console.log("----------websocket连接断开,超出最大重连次数----------"); } }; socketRef.value.onmessage = (event: any) => { onMessageCallback(JSON.parse(event.data)); }; }; // 断开连接 const closeWebSocket = () => { if (socketRef.value && socketRef.value.readyState === 1) { // 禁止断线重连 reconnectAttempts.value = 6; socketRef.value.close(); isConnected.value = false; } }; // 发送消息 const sendMessage = (data: any) => { if (socketRef.value && socketRef.value.readyState === 1) { socketRef.value.send(JSON.stringify(data)); } else { console.error("socket连接异常--------------"); } }; // 生命周期钩子 onMounted(() => { initWebSocket(); }); //页面销毁前,注销关闭socket连接 onBeforeUnmount(() => { closeWebSocket(); }); // 返回暴露的方法和状态 return { isConnected, sendMessage, }; }
useWebSocket使用方法:
import useWebSocket from "./useWebSocket"; const socketUrl = 'ws://xxxxxxxxx' //websocket连接 const { isConnected, sendMessage } = useWebSocket( socketUrl, (message: any) => { // isConnected socket连接状态 true false // sendMessage 数据推送方法 //向成功连接的服务端推送数据 sendMessage({ filed:'hello' }) } );