Home > javascript, node.js, Programming > Learning Node.js + socket.io – a simple streaming example.

Learning Node.js + socket.io – a simple streaming example.

I learned about Node.js not too long ago (Node is actually very new) and found its non-blocking io very interesting. Socket.io is a Node module that enables real-time communication between web client and server. It basically chooses the best supported streaming technology for the client if native streaming technology is not available (Websocket for example). I am a total beginner to both Node and socket.io and I wrote a little more complicated example than the basic one on socket.io home page. In this example, a random number is generated every 4 seconds and broadcasted to the network (see the video link at the end of this post).

Server:
Install socket.io if it’s not installed:
npm install socket.io -g

var io = require('/usr/local/lib/node_modules/socket.io').listen(8080);
var t;  // I usually don't like using global variables but hope it's ok for DEMO's purpose

function rnd() {
    var num=Math.floor(Math.random()*1000);
    return num;
}
io.sockets.on('connection', function (socket) {
    t=setInterval( function() {
        var n=rnd();
        socket.broadcast.emit('stream', {n:n.toString()});
    }, 4000);
    socket.on('action', function (data) {
        console.log('received action');
        if(data.todo=='stop') {
            socket.broadcast.emit('stream', {n:'Stopped'});
            console.log('stopping timer now.');
            clearInterval(t);
        } else if(data.todo='run') {
            // the setInterval code definitely can
            // be combined/optimized with the one above
            // again for DEMO's sake I just leave it as is
            t=setInterval( function() {
                var n=rnd();
                socket.broadcast.emit('stream', {n:n.toString()});
            }, 4000);
        }
    });
});

Client:
Note:
The client socket.io.js code can be found at /usr/local/lib/node_modules/socket.io/node_modules/socket.io-client/dist on my Ubuntu 10.10

client.html, served using Apache (I know this can be changed to use Node.js totally, with some help from Express webframe)

<script src="socket.io.js"></script>
<script>
    var sw='run';
  var socket = io.connect('http://192.168.1.200:8080');

  socket.on('stream', function (data) {
        document.getElementById('number').innerHTML=data.n;
  });

    function stop_timer() {
        if(sw=='run') {
            socket.emit( 'action', {todo: 'stop'} );
            sw='stop';
        } else {
            socket.emit( 'action', {todo: 'run'} );
        }
    }
</script>
<div style="border:1px solid #ccc" id="number">&nbsp;</div>
<a href="#" onclick="stop_timer();return false;">Action</a>

Here’s a quick video made with ScreenFlow (didn’t purchase so pls forgive the watermark):

About these ads
  1. a
    November 10, 2011 at 11:21 am

    Can’t get your example to work. Which version of Node.js you have and version of socket.io?

    • ricoch3n
      November 10, 2011 at 12:01 pm

      Hi,
      Sorry I should have included the version information for that. I remember the version I used for this example was 0.4.7 (I have upgraded to the current 0.6.0 and haven’t tested this example yet with the new version yet). I am not sure how you set up the testing environment especially the web server part. In my example I am using apache (for static files) + node.js + socket.io (last two components for streaming). Also you can let me know any node error output, web server log, firebug console output (assuming you use Firefox) so I help to find out why it doesn’t work for you.

      -Rico

    • June 26, 2012 at 6:38 am

      I think changing the jQuery code in line 7 of client.html would do:
      $(“#number”).html(data.n);
      19:
      Also include the jQuery library
      It worked for me!

  2. June 26, 2012 at 6:38 am

    Anant Gupta (@anantzoid) :
    I think changing the jQuery code in line 7 of client.html would do:
    $(“#number”).html(data.n);
    19:”
    Also include the jQuery library
    It worked for me!

  3. J
    July 29, 2012 at 5:14 pm

    Thanks!! This helped me a lot

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: