websocket封装
自己项目封装使用的,仅供参考。
/**
* websocket 封装
* 自动重连
*/
// export default class MSocket {
export class MSocket {
constructor (config) {
if (!config.url) {
throw new Error('websocket url is invalid')
}
this.reconnectTimer = null
this.heartbeatTimer = null
this.isAlive = false
this.config = {
url: '',
retry: Infinity,
reconnectWait: 5 * 1000,
heartBeatWait: 6 * 1000,
heartMsg: 'test',
isHeartBeat: true
}
Object.keys(config).forEach(key => {
this.config[key] = config[key]
})
this.init()
}
init () {
this.socket = new WebSocket(this.config.url)
this.socket.onerror = (e) => {
this.reconnect()
this.isAlive = false
typeof this.config.onerror === 'function' && this.config.onerror(e)
}
this.socket.onmessage = ({ data }) => {
const res = data.indexOf('{') > -1 ? JSON.parse(data) : data
typeof this.config.onmessage === 'function' && this.config.onmessage(res)
}
this.socket.onclose = (e) => {
this.isAlive = false
console.info('websocket was closed')
typeof this.config.onclose === 'function' && this.config.onclose(e)
}
this.socket.onopen = (e) => {
console.info('websocket was opened')
this.isAlive = true
if (this.config.isHeartBeat) {
this.startHeart()
}
typeof this.config.onopen === 'function' && this.config.onopen(e)
}
}
send (data) {
if (!this.isAlive) return
const text = typeof data === 'string' ? data : JSON.stringify(data)
this.socket.send(text)
}
reconnect () {
this.reconnectTimer = setTimeout(() => {
if (this.config.retry > 0) {
this.config.retry--
this.init()
}
}, this.config.reconnectWait)
}
startHeart () {
this.heartbeatTimer = setInterval(() => {
this.send(this.config.heartMsg)
}, this.config.heartBeatWait)
}
}
使用方法
import { MSocket } from '/your path/socket'
const websocket = new MSocket({
url: 'your ws url',
onerror: (e) => {
console.log(e)
},
onmessage: (data) => {
console.log(data)
}
})
websocket.send('666')