webSocket () {
const that = this
// let socket
if (window.WebSocket) {
let locationOrigin = window.location.origin.replace('http://', '')
let header = 'ws://'
if (window.location.origin.startsWith('https')) {
header = 'wss://'
locationOrigin = window.location.origin.replace('https://', '')
}
that.ws = new WebSocket(header + locationOrigin + '/websocket' + '?' + sessionStorage.getItem('userCode') +
',;' + sessionStorage.getItem('token') + ',;' + sessionStorage.getItem('authToken') + ',;' + '1')
// that.ws = new WebSocket('ws://' + that.webSocketPath)
// 监听socket连接
that.ws.onopen = function () {
// that.ws = socket
that.start()
that.ws.send(
JSON.stringify({
userCode: sessionStorage.getItem('userCode')
})
)
}
// 监听socket消息
that.ws.onmessage = function (msg) {
// 写自己的处理逻辑
console.log('接收message', msg.data)
// 收到服务器信息,心跳重置
// that.reset()
}
// 监听socket错误信息
that.ws.onerror = that.websocketerror()
// 监听socket关闭
that.ws.onclose = that.websocketclose()
}
},
websocketerror () {
// console.log('onerror')
this.reconnect()
},
websocketclose () {
// console.log('onclose')
// this.reconnect()
let that = this
clearInterval(that.timeIntervalObj)
clearTimeout(that.serverTimeoutObj)
},
// 开始心跳
start () {
let self = this
self.timeIntervalObj && clearInterval(self.timeIntervalObj)
self.serverTimeoutObj && clearTimeout(self.serverTimeoutObj)
self.timeIntervalObj = setInterval(function () {
if (self.ws.readyState === 1) {
// 连接正常
self.ws.send('heartCheck') // 发送心跳
// console.log('heartCheck')
} else {
// console.log('timeout-reconnect')
self.reconnect() // 重新连接
}
// self.serverTimeoutObj = setTimeout(function () {
// // 超时关闭
// self.ws.close()
// console.log('timeout-close')
// }, self.timeout)
}, self.timeout)
},
// 重置心跳
reset () {
// console.log('reset')
let that = this
clearInterval(that.timeIntervalObj)
clearTimeout(that.serverTimeoutObj)
that.start()
},
// 重连
reconnect () {
// console.log('reconnect')
let that = this
if (that.lockReconnect) {
return
}
that.lockReconnect = true
that.timeoutnum && clearTimeout(that.timeoutnum)
that.timeoutnum = setTimeout(function () {
// console.log('reconnect-webSocket')
// 新连接
that.webSocket()
that.lockReconnect = false
}, 5000)
},
// 消息相关
ws: null, // WebSocket实例
webSocketPath: 'localhost:13222', // 地址
lockReconnect: false, // 是否真正建立连接
timeout: 8 * 1000, // 心跳检测时间
timeIntervalObj: null, // 心跳心跳倒计时
serverTimeoutObj: null, // 心跳倒计时
timeoutnum: null, // 断开 重连倒计时
uniapp中使用websoket 可参考 uniapp websocket连接 心跳机制_不秃头的小姑娘的博客-CSDN博客