简体   繁体   English

节点Js与response.write的问题

[英]Node Js problems with response.write

When I try to utilize http stream connection for some reason write does not flush until I call response.end() 当我尝试利用http流连接由于某种原因写入不会刷新,直到我调用response.end()
I am taking the code straight from the demo and do not understand what my problem is. 我直接从演示中获取代码,不明白我的问题是什么。
When I curl to the server my headers are correct. 当我卷曲到服务器时,我的标题是正确的。

HTTP/1.1 200 OK
Content-Type: text/plain
Connection: keep-alive
Transfer-Encoding: chunked


var http = require('http');
    http.createServer(function (req, res) {
      res.writeHead(200, {'Content-Type': 'text/plain'});
      res.write('hello');
      res.write(':');
      setTimeout(function(){ 
          res.end('World\n')},
          2000);
    }).listen(1337, "127.0.0.1");
    console.log('Server running at http://127.0.0.1:1337/');

Why is the server not sending the write data? 为什么服务器不发送写入数据?

I seems to be browser specific behavior -- firefox shows the data ("Hello:") immediately while chrome seems to buffer and wait until the response is ended. 我似乎是浏览器特定的行为 - firefox立即显示数据(“Hello:”),而chrome似乎缓冲并等待响应结束。 Note that chrome also shows the data immediately if you write more data at first (eg I wrote 1000 "Hello"s). 请注意,如果您首先编写更多数据,Chrome也会立即显示数据(例如,我写了1000个“Hello”)。

I think I understand what you mean... 我想我明白你的意思......

From the node.js docs: 来自node.js文档:

The first time response.write() is called, it will send the buffered header information and the first body to the client. 第一次调用response.write()时,它会将缓冲的头信息和第一个主体发送到客户端。 The second time response.write() is called, Node assumes you're going to be streaming data, and sends that separately. 第二次调用response.write()时,Node假定您将要传输数据,并单独发送。 That is, the response is buffered up to the first chunk of body. 也就是说,响应被缓冲到第一块体。

http://nodejs.org/docs/v0.4.7/api/all.html#response.write http://nodejs.org/docs/v0.4.7/api/all.html#response.write

(Nice port usage BTW :) ) (好的端口使用BTW :))

Try to check your code with telnet or nc. 尝试使用telnet或nc检查您的代码。 curl usually buffers last line curl通常缓冲最后一行

这是因为你在res.end('World\\n')和逗号之前的位置错过了一个封闭的“}”。

After fixing the missing curly brace, your code is working for me from a browser. 修复缺失的大括号后,您的代码正在通过浏览器为我工作。 Curl from the commandline seems to wait for the full response but wireshark confirms that it does use chunked encoding and the response was split into 2 packages in both cases. 来自命令行的卷曲似乎等待完整响应,但wireshark确认它确实使用了分块编码,并且在两种情况下响应被分成2个包。

I assume that the curl output is line buffered and waiting for the newline after 'World' before it prints anything. 我假设curl输出是行缓冲的,并在打印之前等待'World'之后的换行符。 You can confirm this by printing another newline after 'hello:'. 您可以在'hello:'之后打印另一个换行符来确认这一点。

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

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