Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

event handler sendHandler can not be triggered sometimes #183

Open
wshu001 opened this issue Nov 20, 2020 · 1 comment
Open

event handler sendHandler can not be triggered sometimes #183

wshu001 opened this issue Nov 20, 2020 · 1 comment

Comments

@wshu001
Copy link
Contributor

wshu001 commented Nov 20, 2020

The following send function register event handler this.on('data', sendHandler) too later, sometimes if telnet server send response quickly enough, sendHandler will not be triggered because the response come in before event handler registered, , causing high lever locked if we use waitfor parameter. I have attached a fix for this issue, the fix works perfect in my testing.

index.zip

send(data, opts, callback) {
if (opts && opts instanceof Function) callback = opts

return new Promise((resolve, reject) => {
  if (opts && opts instanceof Object) {
    this.ors = opts.ors || this.ors
    this.sendTimeout = opts.timeout || this.sendTimeout
    this.maxBufferLength = opts.maxBufferLength || this.maxBufferLength
    this.waitfor = (opts.waitfor ? (opts.waitfor instanceof RegExp ? opts.waitfor : RegExp(opts.waitfor)) : false);
  }

  data += this.ors

  if (this.socket.writable) {
    this.socket.write(data, () => {
      let response = ''
      this.state = 'standby'

      this.on('data', sendHandler)

      if (!this.waitfor || !opts) {
        setTimeout(() => {
          if (response === '') {
              this.removeListener('data', sendHandler)
              reject(new Error('response not received'))
              return
          }

          this.removeListener('data', sendHandler)
          resolve(response)
        }, this.sendTimeout)
      }

      const self = this

      function sendHandler(data) {
        response += data.toString()

        if (self.waitfor) {
          if (!self.waitfor.test(response)) return

          self.removeListener('data', sendHandler)
          resolve(response)
        }
      }
    })
  } else {
    reject(new Error('socket not writable'))
  }

}).asCallback(callback)

}

@mkozjak
Copy link
Owner

mkozjak commented Mar 12, 2021

@wshu001 maybe you have a PR tackling this issue?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants