"use strict"; const store_user = require("../store/user.js"); function useWebSocket() { const userStore = store_user.useUserStore(); let ws = null; const connectWebSocket = () => { if (!userStore.isLogined) { console.error("用户未登录,无法建立 WebSocket 连接"); return; } const token = userStore.userInfo.token; const wsUrl = `${"ws://47.99.70.12:48080/app-api"}/chat/${token}`; if (ws) { console.log("WebSocket 已连接"); return; } ws = new WebSocket(wsUrl); ws.onopen = () => { console.log("WebSocket 连接成功"); }; ws.onmessage = (event) => { const message = event.data; console.log("收到消息:", message); }; ws.onerror = (error) => { console.error("WebSocket 错误:", error); }; ws.onclose = () => { console.log("WebSocket 连接关闭"); ws = null; }; }; const sendMessage = (message) => { if (!ws || ws.readyState !== WebSocket.OPEN) { console.error("WebSocket 尚未连接,无法发送消息"); return; } ws.send(message); }; const closeWebSocket = () => { if (ws) { ws.close(); ws = null; } }; return { connectWebSocket, sendMessage, closeWebSocket }; } exports.useWebSocket = useWebSocket;