js websckoet 连接

/**
 * 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: {code: 10191, message: '维持心跳'},
            isHeartBeat: true
        }
        Object.keys(config).forEach(key => {
            this.config[key] = config[key]
        })
        this.init()
    }

    init () {
        this.socket = new WebSocket('ws://192.168.1.103:8999' + 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)
    }
}