在request.js中关闭套接字连接

时间:2018-11-12 15:02:49

标签: javascript node.js sockets tcplistener

我有一个使用'request'模块获取html的程序。

是否有一种方法可以在收到除中止以外的响应之后手动关闭套接字连接,并从该特定请求实例中删除所有侦听器。

主要问题是,随着程序继续发出请求,无论提取完成后是否使用abort(),文件描述符和侦听器的数量都在不断增长。

最后,程序达到maxListeners大小(已设置为20000)后结束。

const request=require('request')
fetchUrl (params, tag, callBack) {
    this.url = params.url
    this.tag = tag
    let headers = { 'User-Agent': params.useragent }
    let options = { followRedirects: false, keepAlive: false, url: params.url, headers: headers, gzip: true, encoding: null }
    let proxy = 'None'
    let userAgent = params.useragent
    
    if (parseInt(ConfigHandler.getConfig().spfUseProxy) === 1) {
      if (parseInt(ConfigHandler.getConfig().spfUseHermesUserAgent) === 1) {
        userAgent = params.useragent + ' Hughes-PFB/' +
          params.agentid + '/' + params.tracetags
        headers['User-Agent'] = userAgent
        headers['Connection'] = 'Close'
      }
      
      proxy = 'http://' + ConfigHandler.getConfig().iosPrefetchProxyIp +
        ':' + ConfigHandler.getConfig().iosPrefetchProxyPort
      options['proxy'] = proxy
    }

    this.httpClient = request.get(options, (err, response, body) => {
      let result = {}
      if (!err) {
        this.response = response
        this.bodyLen = body.length
        logger.debug('%s Response info, %s', this.tag, this.resourceInfo())
        result = {
          statuscode: response.statusCode,
          headers: response.headers,
          body: body
        }
      } else {
        logger.error('%s, fetchUrl() failed! cause=%s, url=%s', JSON.stringify(this), err.message,
          this.url)
      }
      
      if (this.httpClient) {
           logger.debug('%s, fetchUrl() ending connection!', JSON.stringify(this.httpClient))
          this.httpClient.abort()
        }
        if (response && response.socket)         {
          response.socket.destroy()
        } 
      callBack(result, err)
    })
  }

  cancelFetch () {
    if (this.httpClient) {
      logger.debug('%s, Cancelling fetch for url=%s', this.tag, this.url)
      this.httpClient.abort()
      this.httpClient = null
      this.url = null
    }
  this.response.socket.removeAllListeners()
    }
  }

  close () {
    if (this.response && this.response.socket) {

      this.response.socket.destroy()
      //logger.debug('%s, close(), after socket.destroy(), statusTCP=%s', JSON.stringify(this.response), this.response.socket)
    }
    if (this.httpClient) {
      logger.debug('%s, Closing HTTP connection for url=%s', this.tag, this.url)
      this.httpClient.abort()
      this.httpClient = null
      this.url = null
      this.response = null
    }
  }

0 个答案:

没有答案