我想知道是否可以使用 Node.js 将数据从服务器流式传输到客户端。我想向 Node.js 发布一个 AJAX 请求,然后保持连接打开并不断将数据流式传输到客户端。客户端会收到这个流并不断更新页面。
更新:
作为 this answer 的更新- 我不能让它工作。 response.write
在您调用 close
之前不会发送。我已经设置了一个示例程序,用于实现此目的:
Node.js:
var sys = require('sys'),
http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
var currentTime = new Date();
setInterval(function(){
res.write(
currentTime.getHours()
+ ':' +
currentTime.getMinutes()
+ ':' +
currentTime.getSeconds()
);
},1000);
}).listen(8000);
HTML:
<html>
<head>
<title>Testnode</title>
</head>
<body>
<!-- This fields needs to be updated -->
Server time: <span id="time"> </span>
<!-- import jQuery from google -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<!-- import jQuery -->
<script type="text/javascript">
$(document).ready(function(){
// I call here node.localhost nginx ports this to port 8000
$('#time').load('http://node.localhost');
});
</script>
</body>
</html>
使用这种方法,在我调用 close()
之前我什么都得不到。这可能吗,还是我应该采用长轮询方法,而不是在一个进来时再次调用加载函数?
最佳答案
这是可能的。只需使用 response.write () 多次。
var body = ["hello world", "early morning", "richard stallman", "chunky bacon"];
// send headers
response.writeHead(200, {
"Content-Type": "text/plain"
});
// send data in chunks
for (piece in body) {
response.write(body[piece], "ascii");
}
// close connection
response.end();
您可能必须每 30 秒左右关闭并重新打开连接。
编辑:这是我实际测试的代码:
var sys = require('sys'),
http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
var currentTime = new Date();
sys.puts('Starting sending time');
setInterval(function(){
res.write(
currentTime.getHours()
+ ':' +
currentTime.getMinutes()
+ ':' +
currentTime.getSeconds() + "\n"
);
setTimeout(function() {
res.end();
}, 10000);
},1000);
}).listen(8090, '192.168.175.128');
我通过 Telnet 连接到它,它确实给出了分 block 响应。但是要在 AJAX 浏览器中使用它必须支持 XHR.readyState = 3(部分响应)。据我所知,并非所有浏览器都支持这一点。所以你最好使用长轮询(或 Chrome/Firefox 的 Websockets)。
EDIT2:另外,如果你使用 nginx 作为 Node 的反向代理,它有时会想要收集所有的 block 并立即将其发送给用户。你需要调整它。
关于jquery - 使用 Node.js 流式传输数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2558606/