websocket断线重连

1、需求:最近做了一个需要实时展示硬件状态的项目,需要用到websocket,于是在‘sockjs-client’基础上二次封装了一下

2、思路:封装的目的主要是起到一个断线重连的目的,利用websocket断线会触发onclose方法判断是否重连

import SockJS from 'sockjs-client'
let path = 'http://xx.xxx.xx.xxx:28200/sockjs/ws'
function Sock() {
    this.reConnetCount = 1 //记录重连次数
    this.reConnetTimeOut = null //重连定时器
    this.isClose = false //记录是否关闭-关闭后不重连
    this.webSocket = null
}
Sock.prototype.sockConnet = function(msg, callback) {
    this.webSocket = new SockJS(path)
    this.webSocket.onopen = () => {
        clearTimeout(this.reConnetTimeOut)
        this.reConnetTimeOut = null
        this.reConnetCount = 1 //防中途掉线
        if (this.webSocket.readyState == 1) {
            this.webSocket.send(JSON.stringify(msg))
        }
    }
    this.webSocket.onclose = () => {
        if (process.env.NODE_ENV === 'production') {
            clearTimeout(this.reConnetTimeOut)
            this.reConnetTimeOut = null
            if (this.isClose) return
            if (this.reConnetCount < 6) {
                this.reConnetTimeOut = setTimeout(() => {
                    this.sockConnet(msg, callback)
                }, this.reConnetCount * 3000)
                this.reConnetCount++
            } else {
                this.isClose = true
            }
        }
    }
    this.webSocket.onmessage = e => {
        callback(e)
    }
    return this.webSocket
}
Sock.prototype.sockClose = function() {
    this.isClose = true
    clearTimeout(this.reConnetTimeOut)
    this.reConnetTimeOut = null
    this.webSocket.close()
}
export default new Sock()

 

posted @ 2022-01-08 11:15  Pavetr  阅读(487)  评论(0)    收藏  举报