Node.jsを使用してサーバーからクライアントにデータをストリーミングできるかどうかを知りたいです。単一のAJAXリクエストをNode.jsに投稿し、接続を開いたままにして、データをクライアントに継続的にストリーミングしたいと思います。クライアントはこのストリームを受信し、ページを継続的に更新します。
アップデート:
この答えの更新として-私はこれを機能させることができません。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()
。これは可能ですか、それとも、ロード関数が入ってくるときに再度呼び出すという長いポーリングアプローチを使用する必要がありますか?