【发布时间】:2016-04-05 01:14:52
【问题描述】:
我正在尝试将一些音频流式传输到我的服务器,然后将其流式传输到用户指定的服务,用户将向我提供someHostName,它有时不支持该类型的请求。
我的问题是,当它发生时,clientRequest.on('end',..) 永远不会被解雇,我认为这是因为它被传送到 someHostReq,当 someHostName 是“错误”时,它会变得一团糟。
我的问题是:
即使流 clientRequest 管道出现问题,我仍然可以触发 clientRequest.on('end',..) 吗?
如果不是:我如何检测到someHostReq“立即”发生了问题? someHostReq.on('error') 不会启动,除非经过一段时间。
代码:
someHostName = 'somexample.com'
function checkIfPaused(request){//every 1 second check .isPaused
console.log(request.isPaused()+'>>>>');
setTimeout(function(){checkIfPaused(request)},1000);
}
router.post('/', function (clientRequest, clientResponse) {
clientRequest.on('data', function (chunk) {
console.log('pushing data');
});
clientRequest.on('end', function () {//when done streaming audio
console.log('im at the end');
}); //end clientRequest.on('end',)
options = {
hostname: someHostName, method: 'POST', headers: {'Transfer-Encoding': 'chunked'}
};
var someHostReq = http.request(options, function(res){
var data = ''
someHostReq.on('data',function(chunk){data+=chunk;});
someHostReq.on('end',function(){
console.log('someHostReq.end is called');
});
});
clientRequest.pipe(someHostReq);
checkIfPaused(clientRequest);
});
输出:
如果主机名正确:
pushing data
.
.
pushing data
false>>>
pushing data
.
.
pushing data
pushing data
false>>>
pushing data
.
.
pushing data
console.log('im at the end');
true>>>
//continues to be true, that's fine
如果主机名错误:
pushing data
.
.
pushing data
false>>>>
pushing data
.
.
pushing data
pushing data
false>>>>
pushing data
.
.
pushing data
true>>>>
true>>>>
true>>>>
//it stays true and clientRequest.on('end') is never called
//even tho the client is still streaming data, no more "pushing data" appears
如果你认为我的问题是重复的:
这和这个不一样:node.js http.request event flow - where did my END event go?,OP 只是做一个 GET 而不是一个 POST
和这个不一样:My http.createserver in node.js doesn't work?,因为以下都没有发生,所以流处于暂停模式:
您可以通过执行以下任一操作切换到流动模式:
添加一个“数据”事件处理程序来监听数据。
调用 resume() 方法以显式打开流。
调用 pipe() 方法将数据发送到 Writable。
来源:https://nodejs.org/api/stream.html#stream_class_stream_readable
- 和这个不一样:Node.js response from http request not calling 'end' event without including 'data' event,他只是忘了加
.on('data',..)
【问题讨论】:
-
您是否尝试改为收听
close? -
什么是lisyen关闭线程?
-
流有
close事件以及end事件,详见here -
刚试过,
close主机名错误时不会触发事件