有一篇文章:如何在node.js中为客户端http连接设置超时
但没有一个答案会奏效.
所以,我有这样的代码:
var remote_client = http.createClient(myPost, myHost);
var path = '/getData?';
var param = { };
var request = remote_client.request("POST", path,);
// error case
remote_client.addListener('error', function(connectionException){
console.log("Nucleus Error: " + connectionException);
next(connectionException);
});
request.addListener('response', function (response) {
response.setEncoding('utf-8');
var body = '';
response.addListener('data', function (chunk) {
// get the result!
});
});
request.end();
Run Code Online (Sandbox Code Playgroud)
最大的问题是我连接的网址可能会超时.因此,我想设置一个超时,如15秒.如果是,则触发侦听器.
但是,我没有在http.createClient的文档中看到任何超时功能.请指教.谢谢.:)
var foo = setTimeout(function() {
request.emit("timeout-foo");
}, 15000);
// listen to timeout
request.on("timeout-foo", function() { });
request.addListener('response', function (response) {
// bla
// clear counter
clearTimeout(foo);
});
Run Code Online (Sandbox Code Playgroud)
你自己跑吧.
| 归档时间: |
|
| 查看次数: |
5362 次 |
| 最近记录: |