From da277f9c573334bdf97b7819fecb772b47061072 Mon Sep 17 00:00:00 2001 From: lqqyt2423 <974923609@qq.com> Date: Sat, 4 Dec 2021 23:31:08 +0800 Subject: [PATCH] web addon: websocket will reconnect after close --- addon/web/client/src/App.tsx | 45 +++++++++++++++++++++++++++++++----- 1 file changed, 39 insertions(+), 6 deletions(-) diff --git a/addon/web/client/src/App.tsx b/addon/web/client/src/App.tsx index 33cdf73..777b808 100644 --- a/addon/web/client/src/App.tsx +++ b/addon/web/client/src/App.tsx @@ -16,15 +16,21 @@ interface IState { flows: Flow[] flow: Flow | null flowTab: 'Headers' | 'Preview' | 'Response' + wsStatus: 'open' | 'close' | 'connecting' } +const wsReconnIntervals = [1, 1, 2, 2, 4, 4, 8, 8, 16, 16, 32, 32] + class App extends React.Component { private flowMgr: FlowManager private ws: WebSocket | null + private wsUnmountClose: boolean private pageBottom: HTMLDivElement | null private autoScore = false + private wsReconnCount = -1 + constructor(props: any) { super(props) @@ -33,11 +39,13 @@ class App extends React.Component { this.state = { flows: this.flowMgr.showList(), flow: null, - flowTab: 'Headers', // Headers, Preview, Response + wsStatus: 'close', } this.ws = null + this.wsUnmountClose = false + this.pageBottom = null } @@ -47,13 +55,17 @@ class App extends React.Component { componentWillUnmount() { if (this.ws) { + this.wsUnmountClose = true this.ws.close() + this.ws = null } } initWs() { if (this.ws) return + this.setState({ wsStatus: 'connecting' }) + let host if (process.env.NODE_ENV === 'development') { host = 'localhost:9081' @@ -62,8 +74,30 @@ class App extends React.Component { } this.ws = new WebSocket(`ws://${host}/echo`) this.ws.binaryType = 'arraybuffer' - this.ws.onopen = () => { console.log('OPEN') } - this.ws.onclose = () => { console.log('CLOSE') } + + this.ws.onopen = () => { + this.wsReconnCount = -1 + this.setState({ wsStatus: 'open' }) + } + + this.ws.onerror = evt => { + console.error('ERROR:', evt) + this.ws?.close() + } + + this.ws.onclose = () => { + this.setState({ wsStatus: 'close' }) + if (this.wsUnmountClose) return + + this.wsReconnCount++ + this.ws = null + const waitSeconds = wsReconnIntervals[this.wsReconnCount] || wsReconnIntervals[wsReconnIntervals.length - 1] + console.info(`will reconnect after ${waitSeconds} seconds`) + setTimeout(() => { + this.initWs() + }, waitSeconds * 1000) + } + this.ws.onmessage = evt => { const msg = parseMessage(evt.data) if (!msg) { @@ -98,9 +132,6 @@ class App extends React.Component { this.setState({ flows: this.state.flows }) } } - this.ws.onerror = evt => { - console.log('ERROR:', evt) - } } initScrollMonitor() { @@ -141,6 +172,8 @@ class App extends React.Component { const msg = buildMessageMeta(SendMessageType.CHANGE_BREAK_POINT_RULES, rules) if (this.ws) this.ws.send(msg) }} /> + + status: {this.state.wsStatus}