Reputation: 151
I want to make a web page for give the client the news of his friends every 1 second using socket.io + node.js.
My codes :
Client :
var socket = io.connect('http://localhost:port');
socket.on('connect', function(){
socket.emit('hello', 'Hello guest');
});
socket.on('news_by_server', function(data){
alert(data);
});
setInterval(function(){
socket.emit('news', 'I want news :D ');
}, 1000);
server:
var io = require('socket.io').listen(port);
io.sockets.on('connection', function (socket) {
socket.on('hello', function(data){
console.log('new client connected');
});
socket.on('news', function(data){
socket.emit('news_by_server', 1);
});
});
that's the mains codes, but my question is about the INTERVAL, is it good the make realtime news or there's a way better then it.
Upvotes: 11
Views: 27666
Reputation: 22356
There is no need for the client to ask for news. You can force the server if you want to emit every 1 second - as long as there are clients connected, they will receive updates. If there are no clients connected, you will see in the logs that nothing happens.
On the server
setInterval(function(){
socket.emit('news_by_server', 'Cow goes moo');
}, 1000);
On the client
socket.on('news_by_server', function(data){
alert(data);
});
Upvotes: 27
Reputation: 91
That's pretty much the standard way to do it. If you've not already looked the example apps page on socket.io, there's a beibertweet example that does just this using setInterval.
Also there's a slightly more advanced example on this blog.
Plus .. I found Ryan Dahls's intro on YouTube really useful for understanding the basics of node operation.
Hope that helps.
Upvotes: 2