websocket封装

2023-11-16

 //封装

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)
    }


    initSocket(param) {
        this.isActivelyClose = false


        this.websocket.onclose = e => {
            console.log('websocket连接关闭~' + this.param.url)
            this.isConnect = false
            // 如果手动关闭则不进行重连
            if (!this.isActivelyClose) {
                this.reconnectSocket(param)
            }
        }


        this.websocket.onerror = e => {
            console.log('websocket发生异常~' + this.param.url + e)
            this.reconnectSocket(param)
        }


        this.websocket.onopen = () => {
            console.log('websocket已连接~ ' + this.param.url)
            this.isConnect = true
            if (param.hasOwnProperty('msg')) {
                this.send(param.msg || '')
            }
        }


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


    reconnectSocket(param) {
        if (this.isConnect === true) {
            return false
        }
        console.log('websocket 重新连接~ ')
        this.isConnect = true
        this.timeoutNum && clearTimeout(this.timeoutNum)
        this.timeoutNum = setTimeout(() => {
            this.connect(param)
            this.isConnect = false
        }, 1000)
    }


    /**
     * // websocket连接状态下才能进行send
     * @param {*} msg
     * 向服务send的消息
     */
    send(msg) {
        this.websocket.send(JSON.stringify(msg))
    }


    close() {
        this.isActivelyClose = true
        if (this.websocket) {
            this.websocket.close()
        }
    }
}


export default SocketPlugin

//启动与调用/关闭

let  socketConfig = {
        url: '/ints/websocket/test',
        callback: this.getSocketMsg,
        msg: {
          fanId: '01'
        }
     }
let  testSocket = new SocketPlugin(socketConfig)
// 初始化 启动连接,一般在登录时
testSocket.connect()
ps:如果没有重新new socketplugin,所有回调都在getSocketMsg中


//首次启动连接之后,后续如果再次调用,掉用send方法
// 发送消息
testSocket.send(socketConfig.msg)


// 关闭 一般在退出登录时
testSocket.close()

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

websocket封装 的相关文章

随机推荐