简体   繁体   English

在 NodeJS 中模拟发出的“套接字挂断”

[英]Simulate emitted "Socket hang up" in NodeJS

I would like to simulate an emitted "Socket hang up error" by implementing a simple faulty server request/response scenario.我想通过实现一个简单的错误服务器请求/响应场景来模拟发出的“套接字挂断错误”。

Here is a simple faulty server scenario using the native http module.这是一个使用原生http模块的简单故障服务器场景。 The makeRequest function emits the Socket hang up error. makeRequest函数发出Socket hang up错误。

var server = http.createServer((req, res) => {
  console.log('got request');
  res.write('efgh')
  res.end();
});

server.listen(8080, function() {
  makeRequest(() => {
    server.close();
  });
});

function makeRequest(cb) {
  var req = http.request('http://localhost:8080', function(res) {
    console.log('got response')
    res.resume();
    cb();
  })
  req.write('abcd');
}

Any suggestions on how to simulate emitting this error and so I can handle it in the request module pattern below?关于如何模拟发出此错误的任何建议,以便我可以在下面的请求模块模式中处理它? The ultimate test is running the code block below and verifying that by catching the emitted Socket hang up error, the pipe commands will not execute and fail:最终的测试是运行下面的代码块,并通过捕获发出的Socket hang up错误来验证pipe命令将不会执行并失败:

request('https://localhost:8080/doodles.zip')
    .on('error', function(error){ 
        console.log('error requesting base zip file '); 
        console.log(error);
    })
    .on('data', function(chunk){
        console.log('A new chunk: ', chunk);
    })
    .on('end', function(){
        // console.log(output);
        console.log('End GET Request');    
    })    
    .pipe(fs.createWriteStream('doodles.txt'))
        .on('error',function(error){

            console.log('error streaming base zip file');
            console.log(error);

        })
        .on('close',function(){
            console.log('on close of zip pipe to txt');
        });

From the docs: https://github.com/nodejs/node-v0.x-archive/blob/ba048e72b02e17f0c73e0dcb7d37e76a03327c5a/lib/_http_client.js#L164 I Hope this is what you meant.来自文档: https : //github.com/nodejs/node-v0.x-archive/blob/ba048e72b02e17f0c73e0dcb7d37e76a03327c5a/lib/_http_client.js#L164我希望这就是你的意思。 Good Luck祝你好运

function createHangUpError() {
  var error = new Error('socket hang up');
  error.code = 'ECONNRESET';
  return error;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM