WebSocket 类

205 阅读1分钟
 * @docName: socket
 * @Author: wdx
 * @Date: 2021-10-09 23:30:50
 * @LastEditors: wdx
 * @LastEditTime: 2022-01-20 08:01:49
 */
/**
 * @msg: 
 * @param {*}
 * {
 *      url: string 连接地址
 *      msg: JSON   首次连接成功发送的消息
 *      callBack: function 接收消息回调
 * }
 * @method {*}
 *      connect: 连接
 *      send: 发送消息
 *      close: 关闭连接
 */
class SocketPlugin {
    constructor(param) {
        this.websocket = null
        this.isConnect = false
        this.timeoutNum = null
        this.isActivelyClose = false
        this.param = param
    }


    connect() {
        this.websocket = new WebSocket(this.param.url)
        this.initSocket(this.param)
    }


    /**
     * @msg: 监听事件
     * @param {*} param
     * @return {*}
     */
    initSocket(param) {
        this.isActivelyClose = false


        this.websocket.onclose = e => {
            this.isConnect = false
            if (!this.isActivelyClose) {
                this.reconnectSocket(param)
            }
        }


        this.websocket.onerror = e => {
            this.reconnectSocket(param)
        }


        this.websocket.onopen = () => {
            this.isConnect = true
            if (param.hasOwnProperty('msg')) {
                this.send(param.msg || '')
            }
        }


        this.websocket.onmessage = e => {
            param.callback(JSON.parse(e.data))
        }
    }


    /**
     * @msg: 重连测试
     * @param {*} param
     * @return {*}
     */
    reconnectSocket(param) {
        if (this.isConnect === true) {
            return false
        }
        this.isConnect = true
        this.timeoutNum && clearTimeout(this.timeoutNum)
        this.timeoutNum = setTimeout(() => {
            this.connect(param)
            this.isConnect = false
        }, 1000)
    }

    /**
     * @msg: 发送消息
     * @param {*} msg
     * @return {*}
     */
    send(msg) {
        this.isConnect && this.websocket.send(JSON.stringify(msg))
    }


    /**
     * @msg: 关闭连接
     * @param {*}
     * @return {*}
     */
    close() {
        this.isActivelyClose = true
        if (this.websocket) {
            this.websocket.close()
        }
    }
}


export default SocketPlugin