I gave a short presentation at work today on the basics of Twisted. I
tried to cover what I consider Twisted's core networking features:
Protocols, Transports, Reactors, Factories and Deferreds.
Here's the same code I used to demonstrate the first four of those
items:
from twisted.internet import protocol
from twisted.internet import reactor
class CountingEchoProtocol(protocol.Protocol):
def dataReceived(self, data):
self.transport.write(data)
self.factory.incrementCount(len(data))
data_written = self.factory.getCount()
self.transport.write('Wrote %d bytes so far.\r\n' % data_written)
class CountingEchoFactory(protocol.ServerFactory):
protocol = CountingEchoProtocol
def __init__(self, max=24):
self.count = 0
self.max = max
def incrementCount(self, length):
self.count = self.count + length
if self.count >= self.max:
reactor.stop()
def getCount(self):
return self.count
ce_factory = CountingEchoFactory(25)
reactor.listenTCP(2323, ce_factory)
reactor.run()
print 'Wrote %d bytes total.' % ce_factory.getCount()
In prepartion for giving this informal talk, I spent about an hour or so
just digging through the Twisted docs and/or the code answering my own
questions. So hopefully my co-workers and I all got something from this.
Take care. |