websocket封装

该博客介绍了WebSocketPlugin类的实现,用于管理和重连WebSocket连接。类中包含连接、断开、重连及消息发送的方法。在连接关闭或发生异常时,会自动尝试重新连接。使用时,可以通过配置参数启动连接、发送消息和关闭连接,所有回调在指定的回调函数中处理。

 //封装

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

评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值