Skip to content Skip to sidebar Skip to footer

Need Simple Data Push To Browser Using Node.js

On the server side, I use node.js to do some distributed asynchronous ping-pong. I now need to display the results as a real-time chart in a client browser. To keep things simple,

Solution 1:

I'd really recommend taking a look at http://socket.io/ for Node.js. It works on mobile devices, and supports multiple methods for the Comet effect that you desire, utilizing the best option available to the browser.

It's pretty dead simple too, although it does lack channels, but it's an easy workaround using socket.broadcast(msg, [array containing every user except those 'subscribed'])

Solution 2:

Every two seconds server generates a random number r1 in [0,100], then messages client to draw a piechart with r1 and r2=100-r1. Yet to implement the broadcast suggested for multiple clients. Any other suggestions for improvements welcome.

Server side (in coffeescript):

http = require('http')
io = require('socket.io')

server = http.createServer( )

server.listen(8000)

socket = io.listen(server)

myrand = (client) -> setInterval( -> 
    r1 = Math.floor(Math.random()*101)
    r2 = 100-r1
    client.send(String(r1) + ',' + String(r2))
, 2000)

socket.on('connection', (client) -> myrand(client))

Client side (index.html with javascript):

<h1>My socket client</h1><scriptsrc="http://cdn.socket.io/stable/socket.io.js"></script><divid="piechart">
Hello World
</div><script>
socket = new io.Socket('localhost:8000');
socket.connect();
socket.on('message', function(data){
    url = 'http://chart.apis.google.com/chart?cht=p3&chs=250x100&chd=t:' + data + '&chl=Hello|World';  
    document.getElementById('piechart').innerHTML = "<img src="+ url + "></img>";
});
</script>

Post a Comment for "Need Simple Data Push To Browser Using Node.js"