仅使用node.js和socket.io将更新的数据传输到套接字
我从一个url获取数据,然后在一个套接字中发送这些数据,将数据推送到客户端。我现在已经有了使用setTimeout每10秒发送一次数据的代码。我如何修改我的代码,使我只在数据更改时发送数据。目前,数据可能只会每30秒更改一次,因此我会将相同的数据通过套接字发送30秒左右 我正在使用node.js和socket.io。如有任何建议,将不胜感激:) 每10秒调用一次的函数:仅使用node.js和socket.io将更新的数据传输到套接字,node.js,socket.io,Node.js,Socket.io,我从一个url获取数据,然后在一个套接字中发送这些数据,将数据推送到客户端。我现在已经有了使用setTimeout每10秒发送一次数据的代码。我如何修改我的代码,使我只在数据更改时发送数据。目前,数据可能只会每30秒更改一次,因此我会将相同的数据通过套接字发送30秒左右 我正在使用node.js和socket.io。如有任何建议,将不胜感激:) 每10秒调用一次的函数: function sendData(socket){ var thisRef = this; //The u
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);
}
由于您正在处理http请求,请尝试查找http代码,如果它没有更改,它将返回
Not Modified
(我想是302),如果它与它已修改的不同,您可以向客户端发送。我不确定你是否能做到这一点。。但是这是一个观点如果你没有得到302,为什么不缓存以前的响应并将其与新的响应进行比较呢。