Node.js套接字pipe道方法不会pipe最后一个数据包到http响应
我有使用Express作为networking应用程序的节点服务器。
此服务器与另一端TCP服务器创build一个tcp套接字连接。
我正在尝试将tcp数据传递给用户http响应。
它工作正常,但最后的tcp数据包没有pipe道http响应。
所以,下载的网页浏览器下载状态为99.9%。
我的源代码如下。
任何人都可以帮我解决这个问题?
提前致谢。
app.get('/download/*', function(req, res){ var tcpClient = new net.Socket(); tcpClient.connect(port, ip, function() { // some logic }); tcpClient.on('data', function(data) { /* skip ... */ tcpClient.pipe(res); // This method is called once in the 'data' event loop /* skip ... */ }); tcpClient.on('close', function() { clog.debug('Connection closed.'); }); tcpClient.on('end', function() { clog.debug('Connection Ended.'); }); tcpClient.on('error', function(err){ clog.err(err.stack); }); });
这不是你应该如何使用.pipe()
。
当您将stream传输到另一个stream时,您不必自己处理data
事件:所有事情都由pipe道来处理。 而且, data
事件会在每个数据块上发出,这意味着您可能会多次pipe道(stream)stream。
您只需要创build并初始化Socket,然后将其pipe理到您的响应stream:
tcpClient.connect(port, ip, function () { // some logic this.pipe(res); });
编辑:当你精确的评论,第一块包含元数据,而你只想从第二块pipe道。 这是一个可能的解决scheme:
tcpClient.connect(port, ip, function () { // some logic // Only call the handler once, ie on the first chunk this.once('data', function (data) { // Some logic to process the first chunk // ... // Now that the custom logic is done, we can pipe the tcp stream to the response this.pipe(res); }); });
作为一个方面,如果你想在tcpClient
写入响应对象之前添加自定义的逻辑,请查看Transformstream 。 您将然后必须:
- 用您的自定义转换逻辑创build一个转换stream
- 将所有stream一起pipe道:
tcpClient.pipe(transformStream).pipe(res)
。