/** 创建websocket */ import { onUnmounted } from 'vue'; import { useUserStore } from '@/store/modules/user'; interface Params { msg: string; url?: string; } export const useWebsocket = (onMessage: (data: string) => unknown) => { const userStore = useUserStore(); let ws: WebSocket; function start({ msg, url }: Params) { console.log('start msg', msg); console.log({ url }); const defaultUrl = `/skyeye/${userStore.info.userId}`; const path = url || defaultUrl; ws = new WebSocket( `${window.location.protocol.includes('https') ? 'wss://' : 'ws://'}${ window.location.host }/ws_api_bak${path}`, ); //ws = new WebSocket(`ws://172.16.23.144:8800${path}`); ws.onmessage = function (e) { console.log('wx onmessage send params', msg); console.log('ws onmessage from server: ' + e.data); const data = e.data; onMessage(data); }; ws.onopen = () => { if (msg) { ws.send(msg); } }; } function close() { // console.log("ws unmounted", msg); ws?.close(); } onUnmounted(() => { close(); }); return { start }; }; export default useWebsocket;