Tuesday, May 3, 2011

Protocols #6, Character Generator Protocol

In May of 1983, the Character Generator Protocol was introduced in RFC 864. It existed already on computers mainly as a test for terminals (TTYs in that image you can actually see a character test program) to make sure that they could properly display all of the characters in the vastly huge ASCII character set. Now ASCII is a bad joke. The protocol was introduced to do the same thing over networks (an early ping like utility).


In the modern day Internet, the original protocol needs to be amended slightly: the RFC states that the protocol will continue sending information until the client closes the connection; however I made it auto-close after 1000 outputs because eventually node.js runs out of memory and dies. It would also be nice not to have all of your Internet connection lines taken up by three people that never closed their chargen. Without further ado:
#!/usr/bin/nodejs

var net = require('net');
var dgram = require('dgram');

var linewidth = 72; //Width of a line of text on the console.
var str = "";

//Generate from: ! to ~
for(var i = 33; i < 127; i++) {
str += String.fromCharCode(i);
}

//Make sure length is at least 512 bytes (max for udp)
for(var i = str.length; i < 512; i += str.length)
{
str += str;
}


function getline(lineno) {
return str.substr(lineno % (127 - 33), linewidth ) + "\n";
}

//TCP
var tcpserver = net.createServer(function (socket) {
var j = 0;
while(j < 1000)
{
socket.write(getline(j));
j++;
}
socket.end();
})

//UDP
var udpserver = dgram.createSocket("udp4", function (msg, rinfo) {
var ret = new Buffer(str.substr(0, Math.floor(Math.random()*(513))));
udpserver.send(ret, 0, ret.length, rinfo.port, rinfo.address);
});

//Bind and serve (Port 19 is actual)
tcpserver.listen(8019, "127.0.0.1");
udpserver.bind(8019, "127.0.0.1");

As usual the port numbers have been boosted by 8000, so before actually using, change those and the host computer IP addresses.

No comments:

Post a Comment