繁体   English   中英

Node.JS,服务器在请求中间关闭Keep-Alive连接

[英]Node.JS, Server close Keep-Alive connection in middle of request

我有Node.js HTTP服务器,如果传入连接处于空闲状态10秒钟,它将关闭传入连接,还有使用Keep-Alive连接池请求此服务器的客户端。 当我以10秒的间隔开始发送请求时,我会定期收到错误消息ECONNRESET,因为连接是在HTTP请求的中间关闭的。 除了简单的重新发送请求,是否有任何优雅的解决方案?

server.js

var server = require('http').createServer(function(req, res) {
  console.log(new Date(), "Request ", req.method);
  res.end("Nice");
});

server.timeout = 10000;

server.on("connection", function(socket) {
  console.log("New connection");
  socket._created = new Date().getTime();
  socket.on("close", function() {
    var now = new Date().getTime();
    console.log(new Date(), "Socket closed, TTL", (now - socket._created)/1000);
  });
});
server.listen(3000);

client.js

var http = require("http");

var agent = new http.Agent({
  keepAlive: true
});

var reqSent = 0;
var NEED_REQS = 10;
var TIMEOUT = 10000;

function _req() {
  var start = new Date().getTime();
  var req = http.get({
    host: "localhost",
    port: 3000,
    agent: agent
  }, function(res) {
    reqSent++;
    var now = new Date().getTime();
    console.log("Sent:", reqSent, (now - start)/1000);

    if(reqSent >= NEED_REQS) {
      agent.destroy();
      return;
    }
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
    });

    setTimeout(function() {
      _req();
    }, TIMEOUT);
  });
  req.on("error", function(err) {
    console.error(err);
  });
}

_req();

运行client.js

$ node client.js
Sent: 1 0.028
Sent: 2 0.008
Sent: 3 0.002
{ [Error: read ECONNRESET] code: 'ECONNRESET', errno: 'ECONNRESET', syscall: 'read' }

我确实每5秒发送一次请求就重现了您的问题。 nodejs中的默认keepAlive超时为5秒, https: //nodejs.org/api/http.html#http_server_keepalivetimeout

这个针对nodejs的github问题很好地解释了该行为, https://github.com/nodejs/node/issues/20256解决方法是将keepAlive timout客户端设置为小于服务器端超时的值,但是我看不到nodejs中的此类选项, https: //nodejs.org/api/http.html#http_new_agent_options

我认为对此只有一种解决方案-如果获得ECONNRESET,则重新发送请求,我找到了很好的lib,它包装了这样的逻辑https://github.com/FGRibreau/node-request-retry

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM