使用Node.jsstream式传输数据

我想知道是否有可能通过Node.js将数据从服务器stream式传输到客户端。 我想发布一个单一的AJAX请求到Node.js,然后离开连接打开,并不断stream数据到客户端。 客户端将收到这个stream,并不断更新页面。

更新:

作为这个答案的更新 – 我不能得到这个工作。 在您致电close之前,不会发送response.write 。 我已经build立了一个我用来实现这个function的示例程序:

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">&nbsp;</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秒左右closures并重新打开一次连接。

编辑 :这是我实际testing的代码:

 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连接到它,确实给出了分块的响应。 但是在AJAX浏览器中使用它必须支持XHR.readyState = 3(部分响应)。 就我所知,并不是所有的浏览器都支持这个function。 所以你最好使用长轮询(或Chrome / Firefox的Websockets)。

编辑2 :另外,如果你使用nginx作为Node的反向代理,它有时想收集所有的块并一次发送给用户。 你需要调整它。

看看Sockets.io。 它提供了HTTP / HTTPSstream媒体,并使用各种传输方式来实现:

  • 的WebSocket
  • Flash上​​的WebSocket(+ XML安全策略支持)
  • XHR轮询
  • XHR多部分stream媒体
  • 永远Iframe
  • JSONP轮询(针对跨域)

和! 它可以与Node.JS无缝协作。 这也是一个NPM包。

https://github.com/LearnBoost/Socket.IO

https://github.com/LearnBoost/Socket.IO-node

您也可以中止无限循环:

 app.get('/sse/events', function(req, res) { res.header('Content-Type', 'text/event-stream'); var interval_id = setInterval(function() { res.write("some data"); }, 50); req.socket.on('close', function() { clearInterval(interval_id); }); }); 

这是expressjs的一个例子。 我相信没有expressjs会是这样的。