A simple function that serves a JSON string from a database result is broadcasted to the client, using socket.broadcast(). What I wish to do it update the client side when the value changes. Currently, the broadcast function is using setTimeout to broadcast continously every 1 second. Looking at the request logs in Firebug, there is a continuous GET response, which I dont think is a good thing…
Just wondering what the best practice is for using sockets? Are these requests going to kill something? Would a solution be comparing timestamps, or something similar to stop unnecessarily sending requests?
//server-side
function checkData() {
client.query('SELECT * FROM data', function selectCb(err, data) {
socket.broadcast(processData(data));
setTimeout(checkData, 1000);
});
}
//client-side
socket.on('message', function(data) {
$('#container').html(JSON.stringify(JSON.parse(data), null));
});
//sample data
[{
"type":"Statistic1",
"value":65.2,
"timestamp":"2011-04-29T16:22:39.000Z"
},{
"type":"Statistic2",
"value":18.6,
"timestamp":"2011-04-29T16:22:39.000Z"
}]
Thanks for your help!
It depends on the data you are sending. One of the benefits of sockets is that you can choose when to send data to the clients. Save some of the get requests and only broadcast data when you have something new to send.