Skip to content

Commit

Permalink
fix: fix double emit close event
Browse files Browse the repository at this point in the history
feat: add `reconnect` function
  • Loading branch information
starknt committed May 23, 2023
1 parent 077b35e commit 2410f40
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 6 deletions.
7 changes: 7 additions & 0 deletions scripts/g-cmd.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,10 @@ tcp.on('error', console.error)
tcp.on('close', (e) => {
console.log('退出直播间', e)
})

tcp.runWhenConnected(() => {
setTimeout(() => {
console.log('try close')
tcp.close()
}, 5000)
})
34 changes: 28 additions & 6 deletions src/base/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ interface BilibiliLiveEvent extends BuiltinEvent {
msg: Message<any>
live: void
heartbeat: number
reconnect: void
}

export class LiveClient<E extends Record<EventKey, any>> extends EventEmitter<Merge<BilibiliLiveEvent, E>> {
Expand All @@ -32,6 +33,7 @@ export class LiveClient<E extends Record<EventKey, any>> extends EventEmitter<Me
online = 0
closed = true

private close_func_called = false
private socket: ISocket | IWebSocket
private timeout: any
private readonly HEARTBEAT_TIME = this.options.heartbeatTime ?? 30 * 1000
Expand Down Expand Up @@ -168,17 +170,26 @@ export class LiveClient<E extends Record<EventKey, any>> extends EventEmitter<Me
// @ts-expect-error close event
this.emit('close', e)

if (this.options.keepalive) {
if (this.options.keepalive && !this.close_func_called) {
const timer = setTimeout(() => {
clearTimeout(timer)
this.closed = true
this.online = 0
this.live = false
clearTimeout(this.timeout)
// console.log('try reconnect to ', this.roomId)
// @ts-expect-error emit reconnect event
this.emit('reconnect')
this.socket.reconnect()
}, this.RECONNECT_TIME)
}
else {
this.closed = true
this.online = 0
this.live = false
this.close_func_called = false
clearTimeout(this.timeout)
}
})
}

Expand Down Expand Up @@ -209,19 +220,30 @@ export class LiveClient<E extends Record<EventKey, any>> extends EventEmitter<Me
}

close() {
// @ts-expect-error close event
this.emit('close', this.socket.type === 'tcp' ? false : { code: 0, reason: 'close', wasClean: true })

// issue: https://github.com/ddiu8081/blive-message-listener/issues/24
// this.emit('close', this.socket.type === 'tcp' ? false : { code: 0, reason: 'close', wasClean: true })
if (!this.live)
return
return false

this.close_func_called = true

this.live = false
clearTimeout(this.timeout)

if ('end' in this.socket)
this.socket.end()
else
this.socket.close()
return true
}

reconnect() {
this.closed = true
this.online = 0
this.live = false
clearTimeout(this.timeout)
this.close_func_called = false
// @ts-expect-error emit reconnect event
this.emit('reconnect')
this.socket.reconnect()
}
}

0 comments on commit 2410f40

Please sign in to comment.