watch this The wheels are turning, slowly turning. home
TCP in the browser? 2008-07-01

Allen brought to my attention a blog post by Michael Carter about how Orbited now offers a JavaScript API for making TCP connections. I’m not sure how useful this is right now (and I actually mean that I’m not sure, not that I think it’s useless and am trying to avoid saying so), though I can see how if, at some future date it’s possible to make TCP connections without going through a proxy, apps written this way will suddenly make a lot of sense and be easy to port from apps already based on an API like this.



Anyhow, I thought this would be simple to implement with Athena, but I wanted to see how simple. Five minutes later I had this untested code:



# athenatcp.py
from twisted.internet.protocol import ClientCreator, Protocol
from twisted.internet import reactor

from nevow.athena import LiveElement, expose

class TCPElement(LiveElement):
    jsClass = 'Network.TCP'

    @expose
    def connect(self, host, port):
        def connected(proto):
            self.proto = proto
            self.proto.dataReceived = self.dataReceived
            self.proto.connectionLost = self.connectionLost
        cc = ClientCreator(reactor, Protocol)
        d = cc.connectTCP(host, port)
        d.addCallback(connected)
        return d

    @expose
    def write(self, bytes):
        self.proto.transport.write(bytes)

    def dataReceived(self, data):
        self.callRemote('dataReceived', data)

    def connectionLost(self, reason):
        self.callRemote('connectionLost', reason.getErrorMessage())



// athenatcp.js

// import Nevow.Athena

Network.TCP = Nevow.Athena.Widget.subclass('Network.TCP');
Network.TCP.methods(
    function connect(self, host, port) {
        return self.callRemote('connect', host, port);
    },

    function dataReceived(self, bytes) {
        // override this
    },

    function connectionLost(self, reason) {
        // override this
    });



It’d probably be better if connect were actually a factory function returning TCP instances, but the general idea would be the same. Anyone think this is a really great idea? Anyone want to turn this spike into a real library for Athena?