import {authStore} from "@/stores/auth"; export default defineNuxtPlugin(() => { const config = useRuntimeConfig() const { token } = authStore() const ws = reactive({ instance: null as WebSocket | null, isConnected: false, // 修改 connect 方法接收路径和数据对象 connect(path: string, data?: Record) { if (this.instance?.readyState === WebSocket.OPEN) { this.instance.close() } // 构建查询字符串 const queryString =data ? '?' + Object.entries({ token: token.value,...data}) .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`) .join('&') : '' // 构建完整的 WebSocket URL const wsUrl = `${config.public.NUXT_PUBLIC_SOCKET_URL}${path}${queryString}` this.instance = new WebSocket(wsUrl) this.instance.onopen = () => { this.isConnected = true console.log('WebSocket 已连接') } this.instance.onclose = () => { this.isConnected = false console.log('WebSocket 已断开') /* this.reconnect(path, data)*/ } this.instance.onerror = (error) => { console.error('WebSocket 错误:', error) } this.instance.onmessage = (event) => { try { const data = JSON.parse(event.data) this.handleMessage(data) } catch (error) { console.error('消息解析错误:', error) } } }, // 更新重连方法以支持数据对象 reconnect(path: string, data?: Record) { setTimeout(() => { console.log('尝试重新连接...') this.connect(path, data) }, 3000) }, // 发送消息 send(data: any) { if (this.instance?.readyState === WebSocket.OPEN) { this.instance.send(JSON.stringify(data)) } else { console.warn('WebSocket 未连接,无法发送消息') } }, // 关闭连接 disconnect() { if (this.instance) { this.instance.close() this.instance = null } }, // 消息处理 handleMessage(data: any) { // 触发自定义事件,让组件可以监听 window.dispatchEvent(new CustomEvent('ws-message', { detail: data })) } }) return { provide: { ws } } })