最简单的Node.js回显服务器 [英] Simplest nodejs echo server
问题描述
我熟悉nodejs中的流,并且有一个问题:
I am getting acquainted with streams in nodejs and I have a question:
我有可能是最简单的nodejs回显服务器",即简单地通过管道将其返回到响应流的服务器,无论它通过请求流接收到什么. 它有效,但有一个警告.客户端仅在关闭提交流后才收到数据. 这是服务器代码:
I have what I think is the simplest possible nodejs "echo server" ie a server that simple pipes back to the response stream whatever it receives via the request stream. It works but with a caveat. The client only receives the data back after it closes the submitting stream. Here is the server code:
var http = require('http')
var server = http.createServer(function (req, res) {
req.pipe(res);
});
server.listen(8000);
这是我的测试方式:
执行以下操作就可以了
term1> node server.js&
term2> echo 'hello world!'|curl --no-buffer --data-binary @- 'http://localhost:8000'
hello world!
但是,它只能工作是因为echo在完成后会关闭其输出文件描述符,即,服务器在客户端发送完内容之前不会写任何东西:
However, it only works because echo closes its output file descriptor after being done, ie., the server will not write anything until after its client is done sending stuff:
term2>
term2> yes|curl --no-buffer --data-binary @- 'http://localhost:8000'
(这条线永远卡住了)
我希望yes
会很快填充流缓冲区,所以我会开始看到y很快恢复.不幸的是,他们从来没有这样做.
I would expect that yes
will fill stream buffers pretty fast so I would start seeing y's coming back pretty fast. Unfortunately they never do.
这是预期的吗?我应该如何使用溪流/管道以达到预期的效果? 顺便说一下,我不在乎输出是否会成块返回……我知道那是流(或基础文件I/O)执行缓冲的结果.
Is this expected? How should I use the streams/pipes so as they have the desired effect? By the way I don't care whether the output would come back in chunks... I understand that that would be results of streams (or the underlying file i/o) doing their buffering magic.
谢谢您的帮助
推荐答案
好,
我想我知道我在做什么错.
server.js
正常工作...是curl
中断了流水线.
显然,@-
选项将stdin视为文件,即读取其完整内容然后提交.在读取内容时,我找不到如何使curl
管道传输内容的方法.我认为这是不可行的,因为curl
希望将文件的内容视为普通的HTTP帖子形式值.
Ok,
I think I figured out what I was doing wrong.
The server.js
was working fine... it was curl
that was breaking the pipeline.
Apparently, the @-
option treats stdin like a file ,ie reads its full content and then submits it. I couldn't find how to make curl
pipe the contents as they are being read. I think its not feasible because curl
wants to treat the contents of the file as a normal HTTP post form value..
无论如何,我使用一个简单的nodejs客户端修改了上面的示例,该客户端正在执行我想要的操作:
Anyway, I modified the example above using a simple nodejs client that was doing what I wanted:
term2> cat client.js
var http = require('http');
var req = http.request('http://localhost:8000', function(res) {
res.pipe(process.stdout);
});
process.stdin.pipe(req);
term2> yes|node client.js
y
y
...
nodejs流和管道都是岩石!
nodejs streams and pipes rock!!
这篇关于最简单的Node.js回显服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!