使用Node.js流式传输数据 [英] Streaming data with Node.js

查看:607
本文介绍了使用Node.js流式传输数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以使用Node.js将数据从服务器传输到客户端。我想向Node.js发布单个AJAX请求,然后将连接保持打开状态,并不断向客户端传输数据。客户将收到此流并不断更新页面。



更新:



作为这个答案 - 我无法得到这个工作。在调用 close 之前,不会发送 response.write 。我已经创建了一个示例程序来实现这一点:

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(函数(){
res.write(
currentTime.getHours()
+ ':' +
currentTime.getMinutes()$ b $ (8000); b +':'+
currentTime.getSeconds()
);
},1000);
})。

HTML:

 < HTML> 
< head>
< title> Testnode< / title>
< / head>

< body>
<! - 此字段需要更新 - >
服务器时间:< span id =time>& nbsp;< / span>

<! - 从google导入jQuery - >
< script type =text / javascriptsrc =http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js>< / script>

<! - import jQuery - >
< script type =text / javascript>
$(document).ready(function(){
//我在这里调用node.localhost将nginx移植到端口8000
$('#time')。load('http: //node.localhost');
});
< / script>
< / body>
< / html>

在我调用 close()之前, )。这是可能的,或者我应该用一个长期的民意调查方法,而不是我再次调用加载函数时进来?

有可能的。只是使用回复于()多次。



  var body = [hello world,early morning,richard stallman,chunky bacon]; 
//发送头文件
response.writeHead(200,{
Content-Type:text / plain
});

//以大块的形式发送数据
(体内的一块){
response.write(body [piece],ascii);
}

//关闭连接
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()+\\\

);

setTimeout(function(){
res.end();
},10000);

},1000);
})。listen(8090,' 192.168.175.128' );

我通过Telnet连接到它,它确实给出了分块响应。但在AJAX浏览器中使用它必须支持XHR.readyState = 3(部分响应)。就我所知,并非所有的浏览器都支持这一点。因此,您最好使用长轮询(或Chrome / Firefox的Websockets)。


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


I want to know if it is possible to stream data from the server to the client with Node.js. I want to post a single AJAX request to Node.js, then leave the connection open and continuously stream data to the client. The client will receive this stream and update the page continuously.

Update:

As an update to this answer - I cannot get this to work. The response.write is not sent before you call close. I have set up an example program that I use to achieve this:

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>

Using this method I don't get anything back until I call close(). Is this possible or should I go with a long poll approach instead where I call the load function again as one comes in?

解决方案

It is possible. Just use response.write() multiple times.

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();

You may have to close and reopen connection every 30 seconds or so.

EDIT: this is the code I actually tested:

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');

I connected to it by Telnet and its indeed gives out chunked response. But to use it in AJAX browser has to support XHR.readyState = 3 (partial response). Not all browsers support this, as far as I know. So you better use long polling (or Websockets for Chrome/Firefox).

EDIT2: Also, if you use nginx as reverse proxy to Node, it sometimes wants to gather all chunks and send it to user at once. You need to tweak it.

这篇关于使用Node.js流式传输数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆