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, I am presently using the image-based Google chart URL and restricting the amount of data to be plotted. Eventually this client-side display piece will be rich & interactive.
I understand that one of the ways for my server to push the data out to the browser is Comet. I expect there must be a corresponding socket-something on the browser side, so the two should go together.
Q1: For prototyping: what is the simplest way for me to push string data from node.js to my Fir开发者_StackOverflow社区efox 3.6.10 browser? String updates less than 1KB once per second.
Q2: For production: any recommendations for an approach that will work across browsers, including mobile devices? Binary updates order of 100KB per second, no images or video.
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'])
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>
<script src="http://cdn.socket.io/stable/socket.io.js"></script>
<div id="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>
精彩评论