March 2013
Beginner
191 pages
4h 9m
English
The best way to learn about the components of a Twisted application is to dive right into some examples. This chapter will introduce you to the reactor event loop, transports, and protocols through implementations of a few basic TCP servers and clients.
Skim the code for the TCP echo server and client pair in Examples 2-1 and 2-2. The server’s job is to listen for TCP connections on a particular port and echo back anything it receives. The client’s job is to connect to the server, send it a message, receive a response, and terminate the connection.
fromtwisted.internetimportprotocol,reactorclassEcho(protocol.Protocol):defdataReceived(self,data):self.transport.write(data)classEchoFactory(protocol.Factory):defbuildProtocol(self,addr):returnEcho()reactor.listenTCP(8000,EchoFactory())reactor.run()
fromtwisted.internetimportreactor,protocolclassEchoClient(protocol.Protocol):defconnectionMade(self):self.transport.write("Hello, world!")defdataReceived(self,data):"Server said:",dataself.transport.loseConnection()classEchoFactory(protocol.ClientFactory):defbuildProtocol(self,addr):returnEchoClient()defclientConnectionFailed(self,connector,reason):"Connection failed."reactor.stop()defclientConnectionLost(self,connector,reason):"Connection lost."reactor.stop()reactor.connectTCP("localhost",8000