Getting started with Python's Twisted Framework

Last Updated on December 22, 2017


In this article I'm going to be exploring python's twisted framework. I'm working through the Twisted Network Programming Essentials book from O'Reilly.


 $ pip install twisted

The main idea behind Twisted is that it gives us the parallelism of multithreading programming with the ease of reasoning of single threaded programming.


The Reactor

This is the core of Twisted. Here is a simple explanation of what the reactor does with psuedo-code:

while True:
    timeout = timeout_until_next_timed_event()
    events = wait_for_events(timeout)
    events += timed_events_until(now())
    for event in events:

Here's a simple echo server/client example that illustrates how the reactor works. It is composed of and

from twisted.internet import reactor, protocol

class EchoClient(protocol.Protocol):
    def connectionMade(self):
        self.transport.write(u"Hello, world!".encode('utf-8'))

    def dataReceived(self, data):
        print("Server said:", data)

class EchoFactory(protocol.ClientFactory):
    def buildProtocol(self, addr):
        return EchoClient()

    def clientConnectionFailed(self, connector, reason):
        print("Connection failed.")

    def clientConnectionLost(self, connector, reason):
        print("Connection lost.")

reactor.connectTCP("localhost", 8000, EchoFactory())

from twisted.internet import protocol, reactor

class Echo(protocol.Protocol):
    def dataReceived(self,data):

class EchoFactory(protocol.Factory):
    def buildProtocol(self, addr):
        return Echo()

reactor.listenTCP(8000, EchoFactory())

Join my mailing list to get updated whenever I publish a new article.

Thanks for checking out my site!
© 2021 Brian Caffey