Skip to content

Commit

Permalink
fix: Auto disconnect when ping timeout
Browse files Browse the repository at this point in the history
  • Loading branch information
hans00 committed Jan 14, 2020
1 parent 888bced commit 130f5cd
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 5 deletions.
11 changes: 8 additions & 3 deletions client/base.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,13 @@ const eventId = (str) => str.split('').reduce((sum, char, index) => sum + char.c
class WSClientBase extends EventEmitter {
constructor (options = {}) {
super()
this.options = options
this.replicator = new Replicator(options.parserOptions)
this.options = {
parserOptions: options.parserOptions,
pingInterval: options.pingInterval || 30000,
pingTimeout: options.pingTimeout || 1000,
replyTimeout: options.replyTimeout || 5000
}
this.replicator = new Replicator(this.options.parserOptions)
this.connectState = 0
this.internalEvents = ['open', 'close', 'disconnect', 'connect', 'ping', 'pong', 'message', 'binary', 'error']
this.client = null
Expand Down Expand Up @@ -141,7 +146,7 @@ class WSClientBase extends EventEmitter {
const timeOut = setTimeout(() => {
reject(new Error('Response timeout.'))
delete this._event_return[replyId]
}, this.options.replyTimeout || 5000)
}, this.options.replyTimeout)
const getData = (payload) => {
clearTimeout(timeOut)
delete this._event_return[replyId]
Expand Down
6 changes: 5 additions & 1 deletion client/browser.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ class WSClient extends Base {
super.emit('open')
this._heartbeat = setInterval(() => {
this.ping()
}, options.pingInterval || 30000)
}, this.options.pingInterval)
}
this.client.onclose = () => {
super.emit('close')
Expand All @@ -35,7 +35,11 @@ class WSClient extends Base {
}

ping () {
const autoTerminate = setTimeout(() => this.client.close(), this.options.pingTimeout)
this.client.send(Base.getPayload(null, 'ping'))
super.once('pong', () => {
clearTimeout(autoTerminate)
})
}
}

Expand Down
6 changes: 5 additions & 1 deletion client/node.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ class WSClient extends Base {
this.connectState = 1
this._heartbeat = setInterval(() => {
this.ping()
}, options.pingInterval || 30000)
}, this.options.pingInterval)
})
this.client.on('close', () => {
this.connectState = -1
Expand Down Expand Up @@ -44,7 +44,11 @@ class WSClient extends Base {
}

ping () {
const autoTerminate = setTimeout(() => this.client.terminate(), this.options.pingTimeout)
this.client.ping(new Date().valueOf())
super.once('pong', () => {
clearTimeout(autoTerminate)
})
}
}

Expand Down

0 comments on commit 130f5cd

Please sign in to comment.