项目中需要在某些情况主动给浏览器端发送消息,浏览器接收后做相应的处理。实现方法如下:
创建websocket.js:
import store from '@/store'
import Cookie from 'js-cookie'
import {notification } from 'ant-design-vue'
var websocket = null;
let rec; //用来存储延迟请求的代码
let isConnect = false; //连接标识 避免重复连接
let checkMsg = "heartbeat"; //心跳发送/返回的信息
const baseUrl = process.env.VUE_APP_WEBSOCKET_URL // ws的地址
var globalCallback = function () {};
let createWebSocket = () => {
try {
initWebSocket();
} catch (e) {
reConnect();
}
};
//重连
let reConnect = () => {
if (isConnect) return;
rec && clearTimeout(rec);
rec = setTimeout(function () {
createWebSocket();
}, 10000);
};
//关闭连接
let closeWebSocket = () => {
websocket.close();
};
//心跳设置
var heartCheck = {
timeout: 20000,
timeoutObj: null,
start: function () {
this.timeoutObj = setTimeout(function () {
if (isConnect) websocket.send(checkMsg);
}, this.timeout);
},
reset: function () {
clearTimeout(this.timeoutObj);
this.start();
}
};
// 初始化websocket
function initWebSocket() {
const userKey = xxxx // 生成的唯一编码
var ws = baseUrl + '?userKey ='+userKey
websocket = new WebSocket(ws) //
websocket.onmessage = function (e) {
websocketonmessage(e)
}
websocket.onclose = function (e) {
websocketclose(e)
}
websocket.onopen = function () {
websocketOpen()
heartCheck.start();
}
websocket.onerror = function () {
isConnect = false;
reConnect();
}
}
// 接收消息
function websocketonmessage(e) {
if(e && e.data){
try{
...
// 需要处理的事件
}catch(error){
}
}else{
heartCheck.reset();
}
}
// 数据发送
function websocketsend(agentData) {
websocket.send(JSON.stringify(agentData))
}
// 关闭
function websocketclose(e) {
isConnect = false
}
function websocketOpen() {
}
// 将方法暴露出去
export {
createWebSocket,
closeWebSocket
}