socket封装配合store使用
import store from '@/store';
const WSS_URL = 'ws://访问地址’
let Socket = ''
let setIntervalWesocketPush = null
// 建立连接
export function createSocket() {
if (!Socket) {
console.log('建立websocket连接')
Socket = new WebSocket(WSS_URL)
Socket.onopen = onopenWS
Socket.onmessage = onmessageWS
Socket.onerror = onerrorWS
Socket.onclose = oncloseWS
} else {
console.log('websocket已连接')
}
}
// 打开WS之后发送心跳
function onopenWS() {
console.log('监听打开')
sendPing() //发送心跳
// 初始绑定 根据需求来可删
sendWSPush({
type:'bind',
category:''
})
}
// 连接失败重连
function onerrorWS() {
clearInterval(setIntervalWesocketPush)
Socket.close()
createSocket() //重连
}
// WS数据接收统一处理
export function onmessageWS(e) {
// console.log('监听服务器发送的消息',e.data)
// console.log(JSON.parse(e.data))
const data JSON.parse(e.data)
//获取到的数据存在对应的store 数据里面
if (data.code == '104005') {
//调用store里面自定义修改数据的方法
store.commit('setcoilCarcardData', data);
}
}
export function sendWSPush(value) {
// Socket.send(JSON.stringify(value));
if (Socket !== null && Socket.readyState === 3) { //连接失败
Socket.close()
createSocket() //重连
} else if (Socket.readyState === 1) { //连接正常
Socket.send(JSON.stringify(value));
} else if (Socket.readyState === 0) { //准备连接
setTimeout(() => {
Socket.send(JSON.stringify(value));
}, 3000)
}
}
/**关闭WS */
export function oncloseWS(e) {
console.log('websocket 断开: ' + e.code + ' ' + e.reason + ' ' + e.wasClean)
clearInterval(setIntervalWesocketPush)
if(!e.wasClean){
// Socket = ''
createSocket()
}
}
/**发送心跳 */
export function sendPing() {
setIntervalWesocketPush = setInterval(() => {
sendWSPush({ type: 'ping' });
}, 5000)
}
export {Socket}
全局使用:
import {createSocket from '@/api/scoket.js'
//在app.vue created生命周期里面调用方法
async created(){
createSocket()
}
局部使用:
get coilCarcardData(){
return this.$store.state.coilCarcardData;
}
@Watch('coilCarcardData')
watchcoilCarcardData(res){
//获得到的数据自行做相应的处理
}