1. 程式人生 > 其它 >webSocket實時通訊封裝,vue

webSocket實時通訊封裝,vue

class MyWebSocket {
    constructor (sid) {
        this.sid = sid
        this.ws = null
        this.timeOut = 15000 // 超時時間為6s
        this.timeOutTimer = null
        this.serverTimeOutObj = null
        this.lockReconnect = false // 避免重複連線
        this.messageFun = [] // 方法集合
        this.init()
    }

    init () {
        const that 
= this // ws://192.168.88.7:8092/imserver/screen0908
     //
process.env.VUE_APP_SOCKET_URL 此為根據不同的環境配不同的地址
        let socketUrl = process.env.VUE_APP_SOCKET_URL + this.sid 
        socketUrl = socketUrl.replace('https', 'ws').replace('http', 'ws')

        if (that.ws) {
            that.ws.close()
            that.ws 
= null } // FIXME 引數拼接 this.ws = new WebSocket(socketUrl) this.ws.onopen = () => { console.log('socket 開啟') // 傳送心跳檢測 this.heartCheckStart() } this.ws.onmessage = (msg) => { if (msg.data === '連線成功') { console.log(
'socket連線成功') return } const data = JSON.parse(msg.data) if (!data || this.messageFun.length === 0) return that.messageFun.forEach((item) => { item(data) }) // 重置心跳檢測 this.heartCheckReset() } this.ws.onclose = () => { // 解決異常斷開的問題 console.log('socket 斷開') // TODO 重連處理 this.reconnet() } this.ws.onerror = () => { console.log('socket 連接出錯') this.reconnet() } } reconnet () { console.log('socket重連') const that = this if (this.lockReconnect) return // 正在重連的情況下 直接退出 this.lockReconnect = true setTimeout(() => { that.init() that.lockReconnect = false }, 2000) } heartCheckStart () { const that = this this.timeOutTimer = setTimeout(() => { if (!that.ws.readyState === that.ws.OPEN) return // 為啥這麼寫???? 忘了 console.log('傳送心跳') that.ws.send('ping') // 傳送訊息後 超時事件以內沒收到訊息 前端自動斷開連線 that.serverTimeOutObj = setTimeout(() => { console.log('自動斷開') that.ws.close() }, that.timeOut) // 超時 }, this.timeOut) } heartCheckReset () { clearTimeout(this.serverTimeOutObj) clearTimeout(this.timeOutTimer) this.heartCheckStart() } // 添加回調方法 getMsg (fn) { this.messageFun.push(fn) } close () { this.ws.close() } sendMsg (msg) { this.ws.send(msg) } } const mySocket = new MyWebSocket('screen0909') export default mySocket

使用如下