naman
naman

Reputation: 43

How to prevent socket from getting closed in http request

I am receiving this error Error: write EPIPE while making http request in nodejs . I am using http package, how can I prevent this should i pass keep-alive header true in the request.

const req = server.request(options, (res) => {
    console.log(`data reci`)

    res.on('data', (chunk) => {
      console.log(`body`)
    })
  })

  req.on('error', (e) => {
    console.log(`error`)
  })

  req.write(sample_data)
  req.end()
}

Upvotes: 1

Views: 415

Answers (1)

Vl4dimyr
Vl4dimyr

Reputation: 916

HTTP 1.1 was not designed to keep a connection open. It's designed to make a request, get an aswer and then end.

HTTP 2.0 however is a little different and can be used with more control over the request/response and data. (slides)

But if you really want an open connection I would suggest checking out WebSockets. There are some node modules that will make working with WebSockets quite easy. (slides | ws (node module))

Also, for servers in node.js I would recommand taking a look at express. (node module)

For even more streaming check out WebRTC

Upvotes: 1

Related Questions