Tuesday, April 19, 2011

Protocols #5, Quote of the Day

The quote of the day protocol, defined in RFC 865, specifies a standard that when implemented will return a quote when port 17 is connected to in TCP, or when a datagram is sent to it in UDP.

This implementation in Node.js, is similar to the daytime protocol I built earlier, it introduces an array of quotes of which one is randomly chosen to
#!/usr/bin/nodejs
var net = require('net');
var dgram = require('dgram');

var quotes = [
"Time is an illusion. Lunchtime doubly so.\n - Douglas Adams",
"The quieter you become the more you can hear.\n - Baba Ram Dass",
"Wisdom lies in knowing when to remember and when to forget.\n - Ayn Rand",
"Chance favors the prepared mind.\n - Louis Pasteur",
"The advertisement is the most truthful part of a newspaper.\n - Thomas Jefferson",
"To communicate through silence is a link between the thoughts of man.\n - Marcel Marceau",
"There are periods when...to dare, is the highest wisdom.\n - William Ellery Channing"
];

function getquote() {
randno = Math.floor ( Math.random() * quotes.length );
return quotes[randno] + "\n";
}

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

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

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

No comments:

Post a Comment