import { MessageBox } from 'element-ui'
export default class MyWebSocket {
constructor(url) {
if (typeof (WebSocket) === 'undefined') {
MessageBox.alert('该浏览器不支持websocket!')
return
}
this.Socket = null
this.url = url
this.setIntervalWesocketPush = null
this.createSocket()
}
createSocket() {
this.Socket && this.Socket.close()
if (!this.Socket) {
console.log(`建立${this.url}websocket连接`)
this.Socket = new WebSocket(this.url)
this.Socket.onopen = this.onopenWS
this.Socket.onmessage = this.onmessageWS
this.Socket.onerror = this.onerrorWS
this.Socket.onclose = this.oncloseWS
} else {
console.log('websocket已连接')
}
}
/** 打开WS之后发送心跳 */
onopenWS() {
// sendPing()
}
/** 连接失败重连 */
onerrorWS() {
this.Socket.close()
clearInterval(this.setIntervalWesocketPush)
console.log('连接失败重连中')
if (this.Socket.readyState !== 3) {
this.Socket = null
this.createSocket()
}
}
/** WS数据接收统一处理 */
onmessageWS(e) {
window.dispatchEvent(new CustomEvent('onmessageWS', {
detail: {
data: e.data
}
}))
}
/**
* 发送数据但连接未建立时进行处理等待重发
* @param {any} message 需要发送的数据
*/
connecting(message) {
setTimeout(() => {
if (this.Socket.readyState === 0) {
this.connecting(message)
} else {
this.Socket.send(JSON.stringify(message))
}
}, 1000)
}
/**
* 发送数据
* @param {any} message 需要发送的数据
*/
sendWSPush(message) {
if (this.Socket !== null && this.Socket.readyState === 3) {
this.Socket.close()
this.createSocket()
} else if (this.Socket.readyState === 1) {
this.Socket.send(JSON.stringify(message))
} else if (this.Socket.readyState === 0) {
this.connecting(message)
}
}
/** 断开重连 */
oncloseWS() {
clearInterval(this.setIntervalWesocketPush)
console.log('websocket已断开....正在尝试重连')
if (this.Socket.readyState !== 2) {
this.Socket = null
this.createSocket()
}
}
/** 发送心跳
* @param {number} time 心跳间隔毫秒 默认5000
* @param {string} ping 心跳名称 默认字符串ping
*/
sendPing(time = 5000, ping = 'ping') {
clearInterval(this.setIntervalWesocketPush)
this.Socket.send(ping)
this.setIntervalWesocketPush = setInterval(() => {
this.Socket.send(ping)
}, time)
}
}
2.使用
import MyWebSocket from '@/utils/websocket'
initSocket() {
this.dySocket = new MyWebSocket('ws://localhost:13888')
window.WSocket = {
dySocket: this.dySocket,
}
}