项目全局封装webSocket
// 引入webScoket包
import SockJs from 'sockjs-client'
// 创建一个socket类并抛出
export default class Socket {
constructor (param = {}) {
this.param = param
this.reconnectCount = 0
this.socket = null
this.taskRemindInterval = null
this.lockReconnect = false
this.timeout = 12
this.lastMessageTime = null
}
// 连接webScoket
connection = () => {
let { socketUrl } = this.param
this.lastMessageTime = null
// 检测当前浏览器决定用什么socket
if ('WebSocket' in window) {
this.socket = new WebSocket(socketUrl)
} else {
this.socket = new SockJs(socketUrl)
window.onbeforeunload = function () {
this.socket.close()
}
}
this.socket.onopen = this.onopen
this.socket.onmessage = this.onmessage
this.socket.onclose = this.onclose
this.socket.onerror &#