Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

socket.io setinterval way

Tags:

socket.io

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.

like image 537
user1194313 Avatar asked Feb 10 '12 15:02

user1194313


2 Answers

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.

like image 162
Julian Browne Avatar answered Oct 16 '22 20:10

Julian Browne


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);
});
like image 36
First Zero Avatar answered Oct 16 '22 19:10

First Zero