如何在 nodejs 服务器中设置 HTTP Keep-Alive 超时

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12651466/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:22:53  来源:igfitidea点击:

How to set the HTTP Keep-Alive timeout in a nodejs server

node.jshttp-headersexpresskeep-alive

提问by Miguel L.

I'm actually doing some load testing against an ExpressJS server, and I noticed that the response send by the server includes a "Connection: Keep-Alive" header. As far as I understand it, the connection will remain opened until the server or the client sends a "Connection: Close" header.

我实际上正在对 ExpressJS 服务器进行一些负载测试,我注意到服务器发送的响应包含一个“Connection: Keep-Alive”标头。据我所知,连接将保持打开状态,直到服务器或客户端发送“连接:关闭”标头。

In some implementations, the "Connection: Keep-Alive" header comes up with a "Keep-Alive" header setting the connection timeout and the maximum number of consecutive requests send via this connection.

在某些实现中,“Connection: Keep-Alive”标头带有一个“Keep-Alive”标头,用于设置连接超时和通过此连接发送的最大连续请求数。

For example : "Keep-Alive: timeout=15, max=100"

例如:“Keep-Alive: timeout=15, max=100”

Is there a way (and is it relevant) to set these parameters on an Express server ?

有没有办法(是否相关)在 Express 服务器上设置这些参数?

If not, do you know how ExpressJS handles this ?

如果没有,您知道 ExpressJS 是如何处理的吗?

Edit:After some investigations, I found out that the default timeout is set in the node standard http library:

编辑:经过一番调查,我发现节点标准http库中设置了默认超时:

socket.setTimeout(2 * 60 * 1000); // 2 minute timeout

In order to change this:

为了改变这一点:

var http = require('http');

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end("Hello World");
}).on('connection', function(socket) {
  socket.setTimeout(10000);
}).listen(3000);

Anyway it still looks a little bit weird to me that the server doesn't send any hint to the client concerning its timeout.

无论如何,服务器没有向客户端发送有关其超时的任何提示对我来说仍然有点奇怪。

Edit2:Thanks to josh3736 for his comment.

Edit2:感谢 josh3736 的评论。

setSocketKeepAlive is not related to HTTP keep-alive. It is a TCP-level option that allows you to detect that the other end of the connection has disappeared.

setSocketKeepAlive 与 HTTP 保持活动无关。它是一个 TCP 级别的选项,可让您检测连接的另一端是否已消失。

采纳答案by dgo.a

For Express 3:

对于快递 3:

var express = require('express');
var app = express();
var server = app.listen(5001);

server.on('connection', function(socket) {
  console.log("A new connection was made by a client.");
  socket.setTimeout(30 * 1000); 
  // 30 second timeout. Change this as you see fit.
});