前端心跳机制
前言
一、连接后台的地址
VUE_APP_BASE_URL_WEBSOCKET=http://localhost:8080/imServer/
var webSocketUrl = process.env.VUE_APP_BASE_URL_WEBSOCKET;//websocket连接地址
二、创建心跳机制的时间和死亡唤醒时间
1.创建变量声明
代码如下:
warningInfoWebSocket: {
lockReconnect: false, // 是否允许重新连接
timeout: 10000, // 心跳间隔
reTimeout: 10000, // 重连间隔
timeoutTimer: null, // 心跳定时器
reTimeoutTimer: null, // 重连定时器
webSocket: null
},
2.创建websocket
代码如下(示例):
created() {
this.getMeteorologicalRiskWarningInfoTimely();
},
getMeteorologicalRiskWarningInfoTimely() {
this.createWebSocket();
},
createWebSocket() {
let that = this;
let socketUrl = webSocketUrl + JSON.parse(sessionStorage.getItem("token")).uuid
socketUrl = socketUrl.replace("https", "ws").replace("http", "ws");
that.warningInfoWebSocket.webSocket = new WebSocket(socketUrl)
let webSocket = that.warningInfoWebSocket.webSocket;
webSocket.onopen = function () {
console.log('连接成功...')
that.heartCheckStart()
}
webSocket.onerror = function () {
console.log('连接失败...')
that.reConnect()
}
webSocket.onmessage = function (event) {
that.hiddenPointMessage = JSON.parse(event.data)
if (that.hiddenPointMessage.kind==='fast_report'){
that.$refs.meteorological.meteorologicalInfo=that.hiddenPointMessage
// console.log(that.$refs.meteorological.meteorologicalInfo)
that.flightRange(that.hiddenPointMessage.kind);
}else if (that.hiddenPointMessage.kind==='weather_report'){
let newData =[];
newData.push(that.hiddenPointMessage);
that.totalNum = newData.length
that.meteorologicalWarning(that.hiddenPointMessage.kind);
}
that.heartCheckReset()
}
webSocket.onclose = function (event) {
console.log('连接已关闭...')
console.log('websocket 断开: ' + event.code + ' ' + event.reason + ' ' + event.wasClean)
that.reConnect()
}
},
该处使用的url网络请求的数据。
3.心跳机制的检测
heartCheckStart() {
let that = this;
let webSocket = that.warningInfoWebSocket.webSocket;
let timeoutTimer = that.warningInfoWebSocket.timeoutTimer;
let timeout = that.warningInfoWebSocket.timeout;
timeoutTimer = setTimeout(function () {
webSocket.send('HeartBeat')
}, timeout)
},
4.重新开启心跳监测机制
heartCheckReset() {
let that = this;
let timeoutTimer = that.warningInfoWebSocket.timeoutTimer;
clearTimeout(timeoutTimer)
that.heartCheckStart();
},
4.websocket重连
reConnect() {
let that = this;
let lockReconnect = that.warningInfoWebSocket.lockReconnect;
let reTimeoutTimer = that.warningInfoWebSocket.reTimeoutTimer;
let reTimeout = that.warningInfoWebSocket.reTimeout;
if (lockReconnect) {
return
}
lockReconnect = true
// 没连接上会一直重连,设置延迟避免请求过多
reTimeoutTimer && clearTimeout(reTimeoutTimer)
reTimeoutTimer = setTimeout(function () {
that.createWebSocket();
lockReconnect = false;
}, reTimeout)
},
总结
提示:这里对文章进行总结:
在消息队列中,使用http连接中后台中推送的数据必须是进行传递打开的通道,防止通道的堵塞一定要精心改时间的检测。