我的node.js应用程序正在对REST API http://army.gov/launch-nukes
使用http.request
,我需要区分三种可能的情况:
Success
--服务器的回答是肯定的。我知道我的敌人是destroyed.Failure
--我收到了来自服务器的错误,或者无法连接到服务器。我还有敌人。Unknown
--建立到服务器的连接后,我发送了请求--但不确定发生了什么。这可能意味着请求从未到达服务器,或者服务器对我的响应从未到达。我可能刚刚开始了一场世界大战,也可能不是。--正如您所看到的,区分Failure
和Unknown
的情况对我来说非常重要,因为它们具有非常不同的后果和我需要采取的不同操作。
我也非常喜欢使用http Keep-Alive --我能说什么呢,我有点像个战争贩子,计划突然发出很多请求(然后在很长一段时间内什么都不做)
--
问题的核心是如何将连接错误/超时(即Failure
)与请求发送到网络(即Unknown
)后发生的错误/超时分开。
在psuedo-code逻辑中,我希望这样:
var tcp = openConnectionTo('army.gov') // start a new connection, or get an kept-alive one
tcp.on('error', FAILURE_CASE);
tcp.on('connectionEstablished', function (connection) {
var req = connection.httpGetRequest('launch-nukes');
req.on('timeout', UNKNOWN_CASE);
req.on('response', /* read server response and decide FAILURE OR SUCCESS */);
}
)
发布于 2013-10-12 17:12:43
下面是一个示例:
var http = require('http');
var options = {
hostname: 'localhost',
port: 7777,
path: '/',
method: 'GET'
};
var req = http.request(options, function (res) {
// check the returned response code
if (('' + res.statusCode).match(/^2\d\d$/)) {
// Request handled, happy
} else if (('' + res.statusCode).match(/^5\d\d$/))
// Server error, I have no idea what happend in the backend
// but server at least returned correctly (in a HTTP protocol
// sense) formatted response
}
});
req.on('error', function (e) {
// General error, i.e.
// - ECONNRESET - server closed the socket unexpectedly
// - ECONNREFUSED - server did not listen
// - HPE_INVALID_VERSION
// - HPE_INVALID_STATUS
// - ... (other HPE_* codes) - server returned garbage
console.log(e);
});
req.on('timeout', function () {
// Timeout happend. Server received request, but not handled it
// (i.e. doesn't send any response or it took to long).
// You don't know what happend.
// It will emit 'error' message as well (with ECONNRESET code).
console.log('timeout');
req.abort();
});
req.setTimeout(5000);
req.end();
我建议你使用netcat来使用它,即:
$ nc -l 7777
// Just listens and does not send any response (i.e. timeout)
$ echo -e "HTTP/1.1 200 OK\n\n" | nc -l 7777
// HTTP 200 OK
$ echo -e "HTTP/1.1 500 Internal\n\n" | nc -l 7777
// HTTP 500
(以此类推...)
https://stackoverflow.com/questions/19322248
复制相似问题