import { Notification } from 'element-ui'
const soket = {
url: 'ws://xxxxxxxxxxxxxxxxxxxxxxx',
ws: null,
lockReconnect: true,
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
})
}
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
|