// useWebSocket.js import { ref, reactive, onMounted, onUnmounted, onActivated, onDeactivated, } from "vue"; import getWsUrl from "@/assets/js/getWsUrl"; export default function (url) { url = getWsUrl(url); // 重连时间间隔 默认5秒 const reConnectDelay = 5 * 1000; const socket = ref(null); const isConnected = ref(false); const message = ref(""); let timer = null; const sendCallback = reactive([]); const connect = () => { if (socket.value) { socket.value.close(); } socket.value = new WebSocket(url); socket.value.onopen = () => { isConnected.value = true; console.log("WebSocket Connected, url: ", url); sendCallback.forEach((v) => v()); sendCallback.length = 0; }; socket.value.onmessage = (event) => { // 处理接收到的消息 // console.log("Received:", event.data); // 可以在这里通过 emit 发送消息到组件 message.value = event.data; }; socket.value.onerror = (Event) => { console.error("WebSocket Error:", Event, url); WSClose(Event); }; socket.value.onclose = WSClose; }; // 发送数据 const sendData = (data) => { if (socket.value && socket.value.readyState === socket.value.OPEN) { // console.log('send', data, '============='); socket.value.send(data); } else { sendCallback.push(() => sendData(data)); } }; function WSClose(Event) { isConnected.value = false; if (socket.value) { switch (socket.value.readyState) { case 0: socket.value.onopen = () => { socket.value.close(); console.log('链接关闭', url, 'close事件对象:', Event); socket.value = null; // 没有event对象 则为手动关闭 if (Event) { reConnect(); } } break; case 1: socket.value.close(); console.log('链接关闭', url, 'close事件对象:', Event); socket.value = null; // 没有event对象 则为手动关闭 if (Event) { reConnect(); } break; case 2: socket.value.onclose = () => { console.log('链接关闭', url, 'close事件对象:', Event); socket.value = null; // 没有event对象 则为手动关闭 if (Event) { reConnect(); } } break; case 3: console.log('链接关闭', url, 'close事件对象:', Event); socket.value = null; // 没有event对象 则为手动关闭 if (Event) { reConnect(); } break; } } } // 重连 function reConnect() { if (timer) { return false; } timer = setTimeout(() => { timer = null; connect(); }, reConnectDelay); } onMounted(() => { // console.log('socket mount', Date.now(), '============='); console.log("on socket mount", url, "============="); connect(); }); onActivated(() => { if (!socket.value) { console.log("on socket active", url, "============="); connect(); } }); onDeactivated(() => { if (socket.value) { WSClose(); } }); onUnmounted(() => { if (socket.value) { WSClose(); } }); // 返回 socket 对象和状态 return { socket, isConnected, message, sendData }; }