项目使用vue3 + pinia
import { defineStore } from 'pinia';
import { getCurrentInstance } from 'vue';
export const useSocketStore = defineStore('socket', () => {
const { proxy } = getCurrentInstance();
const wsUrl = proxy.$wsUrl;
let socket = null;
let isConnected = false;
let messageCallback = null; // 存储消息回调函数
function connectSocket() {
if (!isConnected) {
socket = new WebSocket(wsUrl);
// 连接建立
socket.addEventListener('open', async () => {
console.log('WebSocket 连接已建立');
isConnected = true;
if (isConnected) {
proxy.submitOk('WebSocket 连接已建立!');
}
});
// 连接错误
socket.addEventListener('error', (event) => {
console.error('WebSocket 错误:', event);
proxy.submitFail('WebSocket 连接错误!');
});
// 连接关闭
socket.addEventListener('close', () => {
console.log('WebSocket 连接已关闭');
isConnected = false;
});
// 监听消息
socket.addEventListener('message', (event) => {
console.log('收到 WebSocket 消息:', event.data);
const eventData = JSON.parse(event.data);
// const eventData = event.data;
console.log('解析获取之后的值:', eventData);
// 调用消息回调函数,并传递消息数据\
if (messageCallback) {
// 调用消息回调函数,并传递消息数据
messageCallback(eventData);
}
});
} else {
console.log('WebSocket 已连接,无需重新连接');
}
}
// 设置消息回调函数
// 设置消息回调函数并返回 Promise
function getMessage(callback) {
messageCallback = callback;
}
// 发送消息
function sendMessage(command, type, payload) {
const data = {
command: command,
type: type,
payload: JSON.stringify(payload) || JSON.stringify({}),
};
console.log('发送消息:', data);
socket.send(JSON.stringify(data));
}
return {
connectSocket,
getMessage,
sendMessage,
};
});
vue 页面使用,省略其他代码
const { connectSocket, getMessage, sendMessage } = proxy.$store.socket.useSocketStore();
function handleLogin() {
// 建立链接
connectSocket();
setTimeout(() => {
proxy.$refs.loginFormRef.validate((valid) => {
if (valid) {
sendMessage('User', 'User_Login', {
name: loginForm.username,
pwd: loginForm.password,
})
// 获取消息
getMessage((eventData) => {
console.log(eventData)
handleLoginCommand(eventData)
});
}
});
}, 1000)
}
标签:WebSocket,socket,console,log,eventData,封装,websocket,vite,const
From: https://www.cnblogs.com/brujie/p/18053643