NodeJS - “socket hang up” after large amount of re

2019-08-10 04:10发布

问题:

I have been stuck on this "socket hang up" error for a couple days now, and I was hoping someone could help me.

I currently have two Node programs set up:

  1. An HTTP server in Node that responds with the same data for every request.
  2. An HTTP server which responds with data from HTTP server 1. for every request.

My code for HTTP server 2. is below.

var http = require('http')
  , https = require('https')
  , server = http.createServer(do).listen(801)
function do(req, res) {
  var getReq = htts.get('http://127.0.0.1', function (getRes) {
    setTimeout(function () {getRes.pipe(res)},1000)
  })
  req.on('close', function () {
    // setTimeout(function () {getReq.abort()},20)
    console.log(++i + ': req closed')
    getReq.abort()
  })
}

The problem is when I send a request to HTTP server 2. and close the request before a response is sent to my browser (I've set a timeout to give me time to abort). If I continually hold down the refresh button, I will receive the "socket hang up" error after an x amount of times, and do not really understand how to fix this. If I set a timer before executing getReq.abort(), the problem happens less often, and if I set the timer to a large number (above 100ms), there isn't an issue at all.

I can consistently replicate the error by executing getReq.abort() right after creating the request, so I believe that it has something to do with aborting between the time the socket is assigned to the request and before the response is sent.

What is wrong with my code, and how do I prevent this from happening?

Thanks