使用socket.io 进行广播?
使用 socket.broadcast() 向客户端广播一个简单的函数,该函数从数据库结果中提供 JSON 字符串。我希望在值发生变化时更新客户端。目前广播功能是使用setTimeout每1秒连续广播一次。查看 Firebug 中的请求日志,有连续的 GET 响应,我认为这不是一件好事......
只是想知道使用套接字的最佳实践是什么?这些请求会杀死某些东西吗?解决方案是否是比较时间戳,或者类似的方法来停止不必要的发送请求?
//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"
}]
感谢您的帮助!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这取决于您发送的数据。套接字的好处之一是您可以选择何时向客户端发送数据。保存一些获取请求,仅在有新内容要发送时广播数据。
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.