import { ElMessage } from "element-plus";// 全局WebSocket实例
let ws = null;
let isConnected = false;
let currentWsUrl = ''; // 用于存储当前的wsUrl
let baseURL = 'ws://XXX.com:8081';const initWebSocket = (wsUrl, sendData) => {return new Promise((resolve, reject) => {// 检查wsUrl是否发生变化if (wsUrl!== currentWsUrl) {// 如果wsUrl发生变化,关闭已有的WebSocket连接if (ws) {ws.close();ws = null;isConnected = false;}currentWsUrl = wsUrl;// 创建新的WebSocket实例ws = new WebSocket(baseURL + wsUrl);}// 连接成功后的回调函数ws.onopen = function (params) {// console.log("客户端连接成功");isConnected = true;// 向服务器发送消息ws.send(JSON.stringify(sendData));};// 从服务器接受到信息时的回调函数ws.onmessage = function (e) {// console.log("收到服务器响应", e.data);var data = e.data;if (data!== undefined) {if (data.indexOf("{")!== -1) {try {let parsedData = JSON.parse(data);resolve(parsedData);} catch (error) {reject(error);}} else {reject(data);}}};// 连接关闭后的回调函数ws.onclose = function (e) {// console.log("关闭客户端连接");isConnected = false;};// 连接失败后的回调函数ws.onerror = function (evt) {ElMessage.error("连接失败了");};if (isConnected) {ws.send(JSON.stringify(sendData));}// 窗口关闭时,关闭websocket连接,防止连接还没断开就关闭窗口,这样服务端会抛异常。window.onbeforeunload = function () {if (ws) {ws.close();ws = null;}};});
};export default initWebSocket;
引入使用
import initWebSocket from "@/utils/webSocket.js";const getData = () => {let sendData = {type: "info",};initWebSocket(globalStore.wsUrl, sendData).then((res) => {if (res?.s === 1) {Object.assign(info, res?.d);} else {ElMessage.error(res?.d);}}).catch((err) => {ElMessage.error("WebSocket出现错误");});
};getData()