gpt4 book ai didi

Node.js HTTP 服务器停止监听

转载 作者:太空宇宙 更新时间:2023-11-03 23:43:48 26 4
gpt4 key购买 nike

我在端口 1338 上设置了一个 HTTP 服务器来监听服务器的 IP。当我第一次启动 Node 时,这工作得很好,但由于某种原因,我遇到了服务器随机停止监听的问题。我已经检查了 Forever 从我的应用程序收集的日志,包括任何未捕获的异常。自启动以来,日志中没有显示任何错误。

我的问题有两个。什么会导致服务器随机停止监听?另外,应该在 Node 中运行什么检查,以便我可以注销导致监听器停止的错误?

下面是我的 HTTP 服务器的代码。

http.createServer(function (req, res) {
var pathname = url.parse(req.url).pathname;
var query = url.parse(req.url, true).query;
var check;
var responseData = '';
if(pathname === '/healthcheck/ticket'){
check = new Date().getTime();
check = check - tickets.lastAction;
if(check < 30000){
responseData = "page ok";
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(responseData);
}
else{
check = check/1000;
responseData = 'Last action taken by the Ticket Generator was ' + check + ' seconds ago';
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(responseData);
}
}
else{
responseData = 'URL NOT FOUND!';
res.writeHead(404, {'Content-Type': 'text/plain'});
res.end(responseData);
}
}).listen(config.eng.port, config.eng.host);

最佳答案

pathname不等于/healthcheck/ticket时,您不会处理这种情况。没有其他分支。

因此,当您的服务器被除 /healthcheck/ticket 之外的其他网址调用时,它永远不会关闭 res 流,因为 res.end() 永远不会被调用。

一段时间后,您的服务器耗尽(网络)资源,因此似乎挂起(即,它不再对新请求使用react)。

解决方案很简单:提供一个 else 分支,并在其中调用 res.end() ,一切都应该没问题。

关于Node.js HTTP 服务器停止监听,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17864161/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com