import store from '@/store/index' import {NotificationBackend} from '@/api/index' class webscoketUtill { constructor(url = '') { //连接地址 this.url = url //连接器 this.ws = null //避免重复连接 this.is_open_scoket = false //心跳时间 this.timeout = 9000 //心跳定时器 this.heartbeatInterval = null //重连次数 this.reconnectionTimes = 9 //多久重连一次 this.reconnectionTimeout = null //连接次数 this.numberConnections = 0 try { this.init() } catch (e) { throw new Error(e) } } init() { //创建webscoket this.ws = new WebSocket(this.url) //监听链接是否成功 this.ws.onopen = (e) => { this.is_open_scoket = true this.numberConnections = 0 clearInterval(this.heartbeatInterval) clearTimeout(this.reconnectionTimeout) this.heartbeat() this.onmessage() this.onclose() } this.onerror() } //接收后端信息 onmessage() { this.ws.onmessage = (e) => { if (this.isJSON(e.data)) { let data = JSON.parse(e.data) if (data.code === 201) { NotificationBackend({ symbol: store.state.currency, time: '30s', client_id: data.data.client_id }) } if (data.code === 202) { let arr = [] data.data.history.forEach(item => { arr.push(JSON.parse(item)) }) store.commit({ type: 'on_K_line_array', data: arr }) } if (data.code === 203) { store.commit({ type: 'onSecondData', data: JSON.parse(data.data) }) } if (data.code === 204) { store.commit({ type: 'onBranchData', data: data.data || false }) } } } } //发送消息 send(val) { let str = '' if (typeof val === 'string') { str = val } else { str = JSON.stringify(val) } this.ws.send(str) } //检测心跳 heartbeat() { this.heartbeatInterval = setInterval(() => { this.send({ code: 1, msg: '狗哥摆烂了' }) }, this.timeout) } //重连 reconnection() { clearInterval(this.heartbeatInterval) clearTimeout(this.reconnectionTimeout) if (!this.is_open_scoket) { if (this.numberConnections < this.reconnectionTimes) { this.close() this.init() this.numberConnections++ this.reconnectionTimeout = setTimeout(() => { this.reconnection() }, 3000) } } } //后端连接断开 onclose() { this.ws.onclose = (e) => { this.is_open_scoket = false this.reconnection() } } close() { this.send({ code: 2, data: '我已关闭!' }) this.ws.close() } //连接失败 onerror() { this.ws.onerror = (e) => { this.is_open_scoket = false this.reconnection() } } //判断是否是json isJSON(str) { if (typeof str === 'string') { try { let obj = JSON.parse(str) if (typeof obj === 'object' && obj) { return true } else { return false } } catch (e) { return false } } } } export default webscoketUtill