Node.js服务器从Twitter获取此JSON流并将其发送给客户端:
stream.twitter.com/1/statuses/filter.json?track=gadget
客户端返回的数据是“分块”JSON。在客户端上使用JSON.parse(chunk)和eval('('+ chunk +')')都会导致解析错误。拼接分块数据并等待“end”事件也不是一个解决方案。我注意到以前的示例在客户端上使用了类似这样的东西,显然以前可以工作:
socket.onmessage = function(chunk) {
data = eval("(" + chunk.data + ")");
alert(data.user.screen_name);
我正在客户端使用这个,但结果却出现了解析错误:
var socket = new io.Socket();
socket.on('message', function(chunk) {
var data = eval('(' + chunk + ')'); // parsing error
alert(data.screen_name):
我知道它能成功返回一个JSON代码块:
var socket = new io.Socket();
socket.on('message', function(chunk) {
alert(chunk): // shows a JSON chunk
服务器:
response.on('data', function (chunk) {
client.each(function(e) {
e.send(chunk);
});
有什么变化或我做错了什么吗?
更新:'end'事件没有触发是因为它正在流式传输?
http.get({
headers: { 'content-type': 'application/json' },
host: 'stream.twitter.com',
path: '/1/statuses/filter.json?track...
}, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
client.each(function(e) {
e.send(chunk);
});
});
// does not fire
res.on('end', function () {
});
...
我正在研究http 1.0和http 1.1在发送分块数据方面的区别。