The Simplest Socket

This time the language was JavaScript (beautiful) and the environment was Mozilla (beastly). Fortunately, the beauty can tame the beast and so we have the simplest socket interface ever. When you create a socket you provide four things (the last two are optional): a host, a port number, what to do when the host sends you data, and what to do if the host closes the connection. Additionally, the socket class has two methods: ‘write’ which lets you write some data, and ‘close’ which closes the connection from your end. For example, if you wanted to see the contents of a web-page, you’d say:

sk = new wlSocket("www.jadetower.org", 80, function(data) { alert(data); })
sk.write("GET / HTTP/1.0\n\n")

That’s all. How do you do the same thing using Mozilla’s built-in Socket capability?

transportService = Components
    .classes["@mozilla.org/network/socket-transport-service;1"]
    .getService(Components.interfaces.nsISocketTransportService)
transport = transportService
    .createTransport(null, 0, "www.jadetower.org", 80, null)
outstream = transport.openOutputStream(0,0,0)
instream = transport.openInputStream(0,0,0)
sriptInstream = Components
    .classes["@mozilla.org/scriptableinputstream;1"]
    .createInstance(Components.interfaces.nsIScriptableInputStream)
sriptInstream.init(instream)
dataListener = {
    onStartRequest: function(request, context) {},
    onStopRequest: function(request, context, status) {
        outstream.close()
        sriptInstream.close()
    },
    onDataAvailable: function(request, context, inputStream, offset, count) {
        alert(sriptInstream.read(count))
    },
}
pump = Components
    .classes["@mozilla.org/network/input-stream-pump;1"]
    .createInstance(Components.interfaces.nsIInputStreamPump)
pump.init(instream, -1, -1, 0, 0, false)
pump.asyncRead(dataListener, null)
outstream.write("GET / HTTP/1.0\n\n")

I wouldn’t say that there’s a right or wrong way to do it: there’s always more than one way to do it. I just prefer the poetic to the prosaic.

The poet’s eye, in fine frenzy rolling, Doth glance from heaven to earth, from earth to heaven; And as imagination bodies forth The forms of things unknown, the poet’s pen Turns them to shapes and gives to airy nothing A local habitation and a name.     (Theseus, Midsummer Night’s Dream V:I)