封装ws.js
export const initWebSocket = class ws {
constructor(url, messagesFn, openData) {
//ws地址
this.wsUrl = url;
//ws初始化发送的消息
this.openData = openData || '初始化websocket连接';
//接收消息的回调
this.messagesFn = messagesFn;
//重连开关
this.reconnectSwitch = true;
//重连定时器
this.reconnectTimer = null;
//心跳定时器
this.keepAliveTimer = null;
//心跳消息
this.keepaliveData = JSON.stringify({
messageType: 'Heartbeat',
message: '心跳检测',
});
//前次发送失败的消息
this.tempSendMessage = '';
//ws对象
this.websock = null;
//初始化ws
this.initWs();
}
//初始化ws
initWs() {
let that = this;
this.websock = new WebSocket(that.wsUrl);
this.websock.onopen = this.onopen.bind(that);
this.websock.onmessage = this.onmessage.bind(that);
this.websock.onclose = (e) => {
that.reconnectWs();
};
this.websock.onerror = (e) => {
that.reconnectWs();
};
}
//ws打开
onopen() {
let that = this;
//关闭旧的定时器
that.clearWsInterval();
//发送初始化消息
if (that.openData) {
this.send(that.openData);
}
//发送前一次发送失败的消息
if (this.tempSendMessage) {
let time = setTimeout(() => {
that.send(that.tempSendMessage);
that.tempSendMessage = '';
clearTimeout(time);
}, 1000);
}
//开启保活机制
this.keepalive();
}
//ws接收到消息
onmessage(message) {
if (message && message.data) {
let res = JSON.parse(message.data);
if (res) {
//调用页面的消息回调方法
this.messagesFn(res);
}
}
}
//ws发送消息
send(agentData) {
try {
this.websock.send(agentData);
} catch (error) {
this.tempSendMessage = agentData;
this.reconnect();
}
}
//主动关闭
close() {
this.reconnectSwitch = false;
this.websock.close();
}
// 重连
reconnectWs() {
if (this.reconnectSwitch) {
this.reconnect();
}
}
//保活心跳
keepalive() {
let that = this;
this.keepAliveTimer = setInterval(() => {
if (that.websock.readyState === 1) {
// console.log('WebSocket的链接已经建立,正在发送心跳信号');
that.websock.send(that.keepaliveData);
}
}, 5 * 60 * 1000);
}
//重连机制
reconnect() {
let that = this;
this.clearWsInterval();
this.reconnectTimer = setInterval(() => {
that.initWs();
}, 3000);
}
//清除保活和重连的定时器
clearWsInterval() {
let that = this;
this.reconnectTimer && clearInterval(that.reconnectTimer);
this.keepAliveTimer && clearInterval(that.keepAliveTimer);
}
};
调用
initSocket() {
const userId = getSession('userId'); //用户id,
const nowDate = new Date().getTime();
const webSocketUrl = `ws://${baseURL.ws}/websocket/${userId}-${nowDate}`;
this.ws = new initWebSocket(webSocketUrl, (e) => {
this.$EventBus.$emit('websocketMessage', e);
});
},