कर रहे सरल तरीका है की एक कम भ्रामक तरीका है।
इसके बजाय 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