文章目录
- 一、websocket 创建并连接
- store / index.ts
- store / modules / websocket / index.ts
- store / modules / websocket / types.ts
- websocket.ts
- 二、websocket 使用
一、websocket 创建并连接
store / index.ts
import { createPinia } from 'pinia';
import useWebsocketStore from './modules/websocket';const pinia = createPinia();export { useWebsocketStore };
export default pinia;
store / modules / websocket / index.ts
export type RoleType = '' | '*' | 'admin' | 'user';
export interface websocketStore {logInfo: [];simraeInfo: [];equipmentInfo: [];serverTime: string;
}
store / modules / websocket / types.ts
import { defineStore } from 'pinia';
import { websocketStore } from './types';const websocketStore = defineStore('websocketStore', {state: (): websocketStore => ({logInfo: [],simraeInfo: [],equipmentInfo: [],}),getters: {getLogInfo() {return this.logInfo;},getSimraeInfo() {return this.simraeInfo;},getEquipmentInfo() {return this.equipmentInfo;},},actions: {setLogInfo(data) {this.logInfo.unshift(data);},setSimraeInfo(data) {this.simraeInfo = data;},setEquipmentInfo(data) {this.equipmentInfo = data;},},
});
export default websocketStore;
websocket.ts
import { useWebsocketStore } from '@/store';const addr = 'http://192.168.1.1:8083/'.replace('http:', 'ws:');
const WSS_URL = `${addr}socket/msg`;
const websocketStore = useWebsocketStore();
let Socket;export function createSocket() {if (!Socket) {console.log('建立连接', WSS_URL);Socket = new WebSocket(WSS_URL);Socket.onopen = openWS;Socket.onmessage = messageWS;Socket.onerror = errorWS;Socket.onclose = closeWS;window.onunload = onunload;}
}export function openWS() {console.log(`WebSocket连接成功 状态码:${Socket.readyState}`);
}export function errorWS() {console.log(`WebSocket连接失败 状态码:${Socket.readyState}`);
}export function messageWS(e) {const newData = JSON.parse(e.data);if (newData.log) {websocketStore.setLogInfo(newData.log);} else if (newData.simRae) {websocketStore.setSimraeInfo(newData);console.log('newData.simRae', newData.simRae);}else {websocketStore.setEquipmentInfo(newData);}// dataStore.setReFreshFlag(e.data + Math.random());
}export function closeWS() {if (Socket && Socket.close !== null) {Socket.close();console.log('关闭连接');}Socket = null;
}export function onunload() {// Socket.close()
}/** 发送心跳 */
export function sendPing() {Socket.send(new Date());// setIntervalWesocketPush = setInterval(() => {// Socket.send('ping')// }, 5000)
}export function sendWSPush() {if (Socket !== null && Socket.readyState === 3) {// if (Socket.close) {// Socket.close()// }// createSocket() // 重连} else if (Socket.readyState === 1) {Socket.send();} else if (Socket.readyState === 0) {setTimeout(() => {Socket.send();}, 60000);}
}
二、websocket 使用
导入
import { createSocket, closeWS } from '@/utils/websocket'
import { onBeforeUnmounted } from 'vue'
连接与关闭
if(WebSocket){createSocket('page1');//创建
}else{alet('当前浏览器不支持websocket')
}onBeforeUnmounted(()=>{closeWS();
})