1. 程式人生 > 其它 >websocket斷線重連

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