问题
I would like to create persistent http connection to host (api.development.push.apple.com) and send POST requests for many paths (for example, '/3/device/1', '/3/device/2', etc.). Will code below create one connection with host or many connections for each http.request()?
var http = require('http');
http.request({
host: 'api.development.push.apple.com',
port: 443,
path: '/3/device/1',
method: 'POST',
}).end();
http.request({
host: 'api.development.push.apple.com',
port: 443,
path: '/3/device/2',
method: 'POST'
}).end();
回答1:
What you want is to use the same Agent for all of your requests.
If you don't specify an agent in the options object, the http module will use the globalAgent, which sets keepAlive to false by default.
So, create your agent, and use it for all requests:
var http = require('http');
var agent = new http.Agent({ keepAlive: true }); // false by default
http.request({
host: 'api.development.push.apple.com',
port: 443,
path: '/3/device/1',
method: 'POST',
agent: agent, // use this agent for more requests as needed
}).end();
来源:https://stackoverflow.com/questions/38608038/node-js-http-create-persistent-connection-to-host-and-sending-request-to-severa