import { Notification } from 'element-ui'
const soket = {
url: 'ws://xxxxxxxxxxxxxxxxxxxxxxx',
ws: null,
lockReconnect: true,
// 实例websocket
websocketFunc() {
try {
if ('WebSocket' in window) {
this.ws = new WebSocket(this.url)
} else {
alert('当前浏览器不支持websocket协议', 3000)
}
this.initEventHandle()
} catch (e) {
this.reconnect()
}
},
// 初始化事件函数
initEventHandle() {
this.ws.onclose = function() {
console.log('报警推送关闭链接')
if (soket.lockReconnect) {
soket.reconnect()
}
}
this.ws.onerror = function() {
soket.reconnect()
}
// 连接成功建立的回调方法
this.ws.onopen = function() {
console.log('消息推送链接成功')
}
// 接收到消息的回调方法
this.ws.onmessage = function(event) {
var res = JSON.parse(event.data)
console.log(res)
Notification({
type: 'success',
title: '消息提醒',
message: res.message,
position: 'top-right',
duration: 0
})
}
// 监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function() {
soket.lockReconnect = false
this.ws.close()
}
},
// 关闭连接
closeWebSocket() {
soket.lockReconnect = false
this.ws.close()
console.log('websocket已关闭!')
},
// 重连
reconnect() {
setTimeout(function() { // 没连接上会一直重连,设置延迟避免请求过多
console.log('尝试重连...' + new Date())
soket.websocketFunc()
}, 2000)
}
}
export default soket
websocket实时推送及重连机制
最新推荐文章于 2024-05-05 11:14:42 发布