有更簡單的方法的不易混淆的方式。
而不是使用的setTimeout或插座直接工作,
我們可以在客戶端中的「選項」使用「超時」使用
下面是服務器和客戶端的代碼,在3個部分。
模塊和選項部分:
'use strict';
// Source: https://github.com/nodejs/node/blob/master/test/parallel/test-http-client-timeout-option.js
const assert = require('assert');
const http = require('http');
const options = {
host: '127.0.0.1', // server uses this
port: 3000, // server uses this
method: 'GET', // client uses this
path: '/', // client uses this
timeout: 2000 // client uses this, timesout in 2 seconds if server does not respond in time
};
服務器部分:
function startServer() {
console.log('startServer');
const server = http.createServer();
server
.listen(options.port, options.host, function() {
console.log('Server listening on http://' + options.host + ':' + options.port);
console.log('');
// server is listening now
// so, let's start the client
startClient();
});
}
客戶端部分:
function startClient() {
console.log('startClient');
const req = http.request(options);
req.on('close', function() {
console.log("got closed!");
});
req.on('timeout', function() {
console.log("timeout! " + (options.timeout/1000) + " seconds expired");
// Source: https://github.com/nodejs/node/blob/master/test/parallel/test-http-client-timeout-option.js#L27
req.destroy();
});
req.on('error', function (e) {
// Source: https://github.com/nodejs/node/blob/master/lib/_http_outgoing.js#L248
if (req.connection.destroyed) {
console.log("got error, req.destroy() was called!");
return;
}
console.log("got error! ", e);
});
// Finish sending the request
req.end();
}
startServer();
如果你把所有的上述3個部分在一個文件中,「一.js「,然後運行:
node a.js
然後,輸出將是:
startServer
Server listening on http://127.0.0.1:3000
startClient
timeout! 2 seconds expired
got closed!
got error, req.destroy() was called!
希望有所幫助。
找到了這個答案(它也可以),但我不知道是否有什麼不同的http.request()http://stackoverflow.com/questions/6129240/how-to-set-timeout-for-http-createclient -in-node-js – Claudio 2011-06-02 13:22:29