You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
115 lines
3.3 KiB
115 lines
3.3 KiB
layui.define(['fms_util', 'jquery'], function (exports) {
|
|
"use strict";
|
|
|
|
const fmsUtil = layui.fms_util
|
|
const $ = layui.jquery
|
|
let websocket = {
|
|
longSock(url, fn, intro = '') {
|
|
let lockReconnect = false //避免重复连接
|
|
const timeout = 30000 // 超时重连间隔
|
|
const HeartBeatMsg = 'HeartBeat'
|
|
let onlineTimes = null
|
|
let ws
|
|
function formatMsg() {
|
|
return JSON.stringify({
|
|
userId: API.userId(),
|
|
content: HeartBeatMsg
|
|
})
|
|
}
|
|
function reconnect() {
|
|
if (lockReconnect) return
|
|
lockReconnect = true
|
|
//没连接上会一直重连,设置延迟避免请求过多
|
|
setTimeout(function () {
|
|
createWebSocket()
|
|
lockReconnect = false
|
|
}, timeout / 3) //这里设置重连间隔(ms)
|
|
}
|
|
//心跳检测
|
|
const heartCheck = {
|
|
timeout,
|
|
timeoutObj: null,
|
|
serverTimeoutObj: null,
|
|
reset: function () {
|
|
clearInterval(this.timeoutObj)
|
|
clearTimeout(this.serverTimeoutObj)
|
|
return this
|
|
},
|
|
start: function () {
|
|
const self = this
|
|
let count = 0
|
|
this.timeoutObj = setInterval(() => {
|
|
if (count < 3) {
|
|
if (ws.readyState === 1) {
|
|
ws.send(formatMsg())
|
|
// console.info(`${intro}HeartBeat第${count + 1}次`)
|
|
}
|
|
count++
|
|
} else {
|
|
clearInterval(this.timeoutObj)
|
|
count = 0
|
|
if (ws.readyState === 0 && ws.readyState === 1) {
|
|
ws.close()
|
|
}
|
|
}
|
|
}, self.timeout)
|
|
}
|
|
}
|
|
const createWebSocket = () => {
|
|
// console.info(`${intro}创建11`)
|
|
ws = new WebSocket(url)
|
|
|
|
ws.onopen = () => {
|
|
ws.send(formatMsg())
|
|
heartCheck.reset().start()
|
|
}
|
|
ws.onmessage = evt => {
|
|
let { data } = evt
|
|
try {
|
|
data = JSON.parse(data)
|
|
} catch (error) {
|
|
data = {}
|
|
}
|
|
if (data.realMessageEnum === 1) {
|
|
heartCheck.reset().start()
|
|
if (data.content === HeartBeatMsg) {
|
|
onLine() // 设置在线状态
|
|
clearTimeout(onlineTimes) // 清除计时器
|
|
onlineTimes = setTimeout(() => { // 如果超过2个心跳时间没返回则视为离线
|
|
offLine()
|
|
}, timeout * 2);
|
|
}
|
|
} else if (data.realMessageEnum === 2) {
|
|
ws.close()
|
|
data.content && fmsUtil.msg(data.content)
|
|
setTimeout(() => {
|
|
User.config({
|
|
jquery: $
|
|
});
|
|
User.method().delUser()
|
|
window.top.location.reload()
|
|
}, 2000);
|
|
} else {
|
|
heartCheck.reset().start()
|
|
fn(data, ws)
|
|
}
|
|
}
|
|
ws.onclose = e => {
|
|
if (e.code !== 1000) {
|
|
reconnect()
|
|
} else {
|
|
clearInterval(heartCheck.timeoutObj)
|
|
clearTimeout(heartCheck.serverTimeoutObj)
|
|
}
|
|
}
|
|
ws.onerror = function (intro) {
|
|
offLine()
|
|
reconnect() //重连
|
|
}
|
|
}
|
|
createWebSocket()
|
|
return ws
|
|
}
|
|
}
|
|
exports('websocket', websocket);
|
|
})
|