有更简单的方法。
代替使用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();
如果将以上三个部分全部放在一个文件“ a.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!
希望能有所帮助。