My first play with node.js.

I’ve been reading a lot about node.js and today I started playing with it.

If you haven’t heard about node.js than you should know that node.js it’s a server that runs V8 javascript. You should definitely go check it out!

After playing with it for a few minutes I have a few words that are spinning in my mind right now and that’s because I’m sure the chatter about these words will heavily increase soon:

javascript, node.js, mongodb, canvas.

Without talking to much about it, see what you can accomplish in a few minutes of playing with node.js: drawme.hortopan.com

 

That’s an ugly crude and simple multi-user live “drawing board”. It’s simple fun and games in only a few lines of code.

Check out the server side code (node.js):

var app = require('http').createServer(handler)
  , io = require('socket.io').listen(app)
  , fs = require('fs')
 
app.listen(8080);
 
function handler (req, res) {
  fs.readFile(__dirname + '/index.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }
 
    res.writeHead(200);
    res.end(data);
  });
}
 
var colorData = {};
var clients = 0;
 
io.sockets.on('connection', function (socket) {
  socket.emit('connected', {data:colorData});
 
  clients = clients + 1;
  socket.emit('connections', clients);
  socket.broadcast.emit('connections', clients);
 
  socket.on('ping', function (data) {
          colorData[data.pos] = data.color;
          socket.broadcast.emit('pong', data);
          io.sockets.emit('pong',data);
  });
 
  socket.on('disconnect', function(){
          clients = clients - 1;
          socket.broadcast.emit('connections', clients);
  });
 
});

Everything about this is possible by using web sockets. Even though only Chrome and Safari support this html5 feature, socket.io does the great job of implementing a flash plugin for the other browsers and that means your thing can work on any browser including Internet Explorer. It’s still faster on Chrome and Safari but the flash plugin does it’s job.

You can download the whole source code for the test above here.

This entry was posted in Internet and tagged , , , , , , , , , . Bookmark the permalink.

2 Responses to My first play with node.js.

  1. Pingback: Cheatsheet: 2011 08.23 ~ 08.31 - gOODiDEA.NET

  2. Nymo says:

    Node is a cool tool

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">