添加连接超时处理

This commit is contained in:
lyswhut 2023-08-28 16:08:08 +08:00
parent 5a69be8c7b
commit 9775e7dca6

View File

@ -31,6 +31,7 @@ const heartbeatTools = {
failedNum: 0,
maxTryNum: 100000,
stepMs: 3000,
connectTimeout: null as NodeJS.Timeout | null,
pingTimeout: null as NodeJS.Timeout | null,
delayRetryTimeout: null as NodeJS.Timeout | null,
handleOpen() {
@ -50,15 +51,16 @@ const heartbeatTools = {
}, 30000 + 1000)
},
reConnnect() {
if (this.pingTimeout) {
clearTimeout(this.pingTimeout)
this.pingTimeout = null
}
this.clearTimeout()
// client = null
if (!client) return
if (++this.failedNum > this.maxTryNum) {
this.failedNum = 0
sendSyncStatus({
status: false,
message: 'Connect error',
})
throw new Error('connect error')
}
@ -81,6 +83,10 @@ const heartbeatTools = {
}, waitTime)
},
clearTimeout() {
if (this.connectTimeout) {
clearTimeout(this.connectTimeout)
this.connectTimeout = null
}
if (this.delayRetryTimeout) {
clearTimeout(this.delayRetryTimeout)
this.delayRetryTimeout = null
@ -92,7 +98,32 @@ const heartbeatTools = {
},
connect(socket: LX.Sync.Socket) {
console.log('heartbeatTools connect')
this.connectTimeout = setTimeout(() => {
this.connectTimeout = null
if (client) {
try {
client.close(SYNC_CLOSE_CODE.failed)
} catch {}
}
if (++this.failedNum > this.maxTryNum) {
this.failedNum = 0
sendSyncStatus({
status: false,
message: 'Connect error',
})
throw new Error('connect error')
}
sendSyncStatus({
status: false,
message: 'Connect timeout, try reconnect...',
})
this.reConnnect()
}, 2 * 60 * 1000)
socket.addEventListener('open', () => {
if (this.connectTimeout) {
clearTimeout(this.connectTimeout)
this.connectTimeout = null
}
this.handleOpen()
})
socket.addEventListener('message', ({ data }) => {
@ -128,7 +159,7 @@ export const connect = (urlInfo: LX.Sync.UrlInfo, keyInfo: LX.Sync.KeyInfo) => {
funcsObj: {
...callObj,
finished() {
toast('Sync connected.')
toast('Sync connected')
client!.isReady = true
sendSyncStatus({
status: true,