我从网址获取数据,然后我将这些数据发送到套接字以将数据推送到客户端。我目前有代码使用setTimeout每10秒发送一次数据。我如何改进我的代码,以便我只发送数据,如果它发生了变化。目前,数据可能每30秒才会更改,因此我将相同的数据发送到套接字大约30秒。
我正在使用node.js和socket.io。任何建议将不胜感激:)
每10秒调用一次的函数:
function sendData(socket){
var thisRef = this;
//The url we want is "myserver:8000/"
var options =
{
host: 'myserver',
path: '/getdata?param1=1¶m2=1738517',
//since we are listening on a custom port, we need to specify it by hand
port: '8000',
//This is what changes the request to a GET request
method: 'GET'
};
callback = function(response)
{
var str = ''
response.on('data', function (chunk) {
str += chunk;
});
response.on('end', function () {
console.log(str);
socket.emit('timeUpdate', { currentTime: str });
});
}
var req = http.request(options, callback);
//This is the data we are posting, it needs to be a string or a buffer
req.write("Hello World!");
req.end();
setTimeout(function()
{
sendData.call(thisRef,socket)
},10000);
}