与Superagent保持联系

时间:2013-12-23 12:25:01

标签: node.js http keep-alive superagent

我正在运行一个node.js服务器A,它使用superagent向另一台服务器B发出HTTP请求。

我调查了服务器B上的请求,看到标题connectionclose,httpVersion为1.1

var http = require('http');
var request = require('superagent');

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.write('req.httpVersion seen on server:' + req.httpVersion);
  res.write('\nreq.headers.connection seen on server:' + req.headers.connection);
  res.end();
}).listen(1337, '0.0.0.0');

request
  .get('localhost:1337/helloword')
  .end(function (err, res) {
    console.log(res.text);
  });

这导致:

req.httpVersion seen on server:1.1
req.headers.connection seen on server:close

但是,如果我从浏览器访问同一台服务器,我会得到:

req.httpVersion seen on server:1.1
req.headers.connection seen on server:keep-alive

http://tools.ietf.org/html/rfc2616#page-172我了解到keep-alive是HTTP 1.1的默认值,除非使用Connection: close另行声明。

所以,我的问题是:

  • 为什么Superagent / Node.js明确设置请求不使用keep-alive / persistent连接?
  • 如何强制Superagent / Node.js使用keep-alive连接?
  • 如何进一步影响确切的行为(保持开放的连接数,超时数等)?

3 个答案:

答案 0 :(得分:8)

似乎没有记录,但您可以使用函数agent将http代理传递给superagent。 因此,您可以使用此模块创建一个保持活动的代理:https://www.npmjs.org/package/agentkeepalive并将其传递给superagent。

这样的事情:

util = require('util');
util.debuglog = require('debuglog');
var http = require('http');
var request = require('superagent');
var Agent = require('agentkeepalive');

var keepaliveAgent = new Agent({
  maxSockets: 100,
  maxFreeSockets: 10,
  timeout: 60000,
  keepAliveTimeout: 30000 // free socket keepalive for 30 seconds
});

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.write('req.httpVersion seen on server:' + req.httpVersion);
  res.write('\nreq.headers.connection seen on server:' + req.headers.connection);
  res.end();
}).listen(1337, '0.0.0.0');

request
  .get('localhost:1337/helloword')
  .agent(keepaliveAgent)
  .end(function (err, res) {
    console.log(res.text);
  });

答案 1 :(得分:1)

浏览器可以重用套接字句柄,因此它会将标头Connection: keep-alive发送到服务器。

如果你想保持连接,可以像这样发送标题:

request
.get('localhost:1337/helloword')
.set('Connection', 'keep-alive')
.end(function (err, res) {
   console.log(res.text);
});

答案 2 :(得分:0)

对于超级代理,还可以使用.timeout(5000)。

                    await superagent.get(`${anyurl}`, { rejectUnauthorized: false })
                        .set({ "Accept": "application/json", "Content-Type": "application/json", })
                        .auth(username, password, { "type": "auto" })
                        .timeout(1000)