Getting started with Python's Twisted Framework

Last updated December 22, 2017

png

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.

Installation

 $ 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.

png

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:
        event.process()

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

echoclient.py

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)
        self.transport.loseConnection()

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

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

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

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

echoserver.py

from twisted.internet import protocol, reactor

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

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

reactor.listenTCP(8000, EchoFactory())
reactor.run()


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

Thanks for checking out my site!
© 2024 Brian Caffey