我已成功使用nodejs和socket.io将大型json文件从服务器发送到客户端,但我对下一步感到困惑:我需要分析json,并且只将更改发送到客户端,以便我在客户端进行非常快速的实时更新,而不必每秒发送整个json。我担心我会遗漏一些非常基本的东西。它目前正在一遍又一遍地发送整个json。我看到发生了什么,我只是不知道如何发送,而只是发送。想法?
服务器:
/*************************** Require modules ********************************/
var app = require('express')()
, request = require('request')
, fs = require('fs')
, http = require('http')
, server = require('http').createServer(app)
, io = require('socket.io').listen(server);
/************************* Start socket server ******************************/
server.listen(8127);
// socket.io
io.sockets.on('connection', function(socket){
var options = {
host: 'host.com',
port: 80,
path: '/api/tomyjson.json',
headers: {
'Authorization': 'Basic ' + new Buffer('username' + ':' + 'password').toString('base64')
}
};
function getStreams() {
http.get(options, function(response){
var data = "";
response.on('data', function(chunk) {
data += chunk;
});
response.on('end', function() {
socket.emit('news', JSON.parse(data));
});
});
}
setInterval(getStreams, 5000);
socket.on('message', function(data){
console.log(data)
})
socket.on('disconnect', function(){
})
});
客户端JS :
var socket = io.connect('host.com:8127/');
socket.on('news', function (json) {
$.each(json.data, function(i, x) {
console.log(x.json.element);
$('#stream-container').prepend(x.json.element);
})
socket.emit('my other event', { my: 'data' });
});
socket.on('message', function(data){
// Do some stuff when you get a message
oldData += data;
document.getElementById('stream-container').innerHTML = oldData;
});
socket.on('disconnect', function(){
// Do some stuff when disconnected
});