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