conan1992 / blog

记录下知识点..
3 stars 0 forks source link

websocket重连 #61

Open conan1992 opened 4 years ago

conan1992 commented 4 years ago
var ws = new WebSocket("ws://xxx")
ws.onopen = function(){
    heartCheck.reset().start()
    console.log("open")
}
ws.onmessage = function(){
    heartCheck.reset().start()
    console.log("msg")
}
ws.onclose = function(){
    reconnnect()
    console.log("close")
}
ws.onerror = function(){
    reconnnect()
    console.log("error")
}
var heartCheck = {
    timeout: 3000,
    timer: null,
    start: function(){
        let self = this;
        self.timer = setTimeout(function(){
            ws.close()
        }, self.timeout)
    },
    reset: function(){
        clearTimeout(this.timer);
        return this;
    }
}

参考