Tuesday, April 19, 2011

Protocols #2, Echo 2.0

To the point, in this article I'll build the echo protocol in 17 lines of code, including whitespace and comments.

Let's face it, C is a very cumbersome language to program network communications in.  Java and Python are only slightly better, but what about JavaScript?

Introducing: Node.js, it has the speed of the V8 engine, the ability to be dynamic like Python, and well, has Java in the name! (Nobody really likes you Java, you are a necessary evil that was invented to run on toasters so they could talk to the blender.)


What is Node?
Node is essentially a JavaScript runtime built on top of V8 that introduces sockets, and file I/O.  And it is non-blocking, which is awesome.

What is non-blocking?
I'm glad you asked. Imagine, if you will your Apache Server, it is running multiple threads, and as soon as a connection is made, one thread takes that connection and serves it until the connection is terminated. If you want a thousand people to connect, you need a thousand threads.

Node on the other hand, takes connections similarly, except everything is based upon callbacks. When a connection is made, a function is called, let's say is to render a PHP page, Node hooks a callback to the end, and forgets about it; returning to service more connections. When the PHP page is finally done reading from the disk, connecting to the database, and running code, the page is returned to Node, who places it on the output stack, and will eventually send it away. This makes Node highly efficient as it never waits for one operation to complete before the next is started.

There is one more thing to love about node though, remember that 205 line echo protocol I wrote in C? How does 17 lines sound, where the whole thing handles both TCP and UDP simultaneously, along with as many connections as I want?

//Echo Protocol RFC 862
var net = require('net');
var dgram = require('dgram');

//TCP
var tcpserver = net.createServer(function (socket) {
socket.pipe(socket);
})

//UDP
var udpserver = dgram.createSocket("udp4", function (msg, rinfo) {
udpserver.send(msg, 0, msg.length, rinfo.port, rinfo.address);
});

//Bind and serve
tcpserver.listen(8007, "127.0.0.1");
udpserver.bind(8007, "127.0.0.1");

I predict home brew protocols are going to be on the rise with Node, when development gets this easy there is sure to be lots of innovation.

No comments:

Post a Comment