Using The Protocol
Using The Protocol
listen tells the reactor to handle connections to the endpoints address using a particular protocol, but the reactor needs to be running in order for it to do anything. reactor.run() starts the reactor and then waits forever for connections to arrive on the port youve specified. This protocol responds to the initial connection with a well known quote, and then terminates the connection. The connectionMade event is usually where set up of the connection object happens, as well as any initial greetings (as in the QOTD protocol above, which is actually based on RFC 865). The connectionLost event is where tearing down of any connection-specific objects is done. Here is an example: from twisted.internet.protocol import Protocol class Echo(Protocol): def connectionMade(self): self.factory.numProtocols = self.factory.numProtocols+1 if self.factory.numProtocols > 100: self.transport.write("Too many connections, try later") self.transport.loseConnection() def connectionLost(self, reason): self.factory.numProtocols = self.factory.numProtocols-1 def dataReceived(self, data): self.transport.write(data) Here connectionMade and connectionLost cooperate to keep a count of the active protocols in the factory. connectionMade immediately closes the connection if there are too many active protocols. Using the Protocol In this section, I will explain how to run a server which uses your Protocol. (In order to see how you should write a production-grade Twisted server, though, you should read the Writing Plug-Ins for Twisted (page 151) HOWTO as well). Here is code that will run the QOTD server discussed earlier: factory = Factory() factory.protocol = QOTD # 8007 is the port you want to run under. Choose something >1024 endpoint = TCP4ServerEndpoint(reactor, 8007)
endpoint.listen(factory) reactor.run() In this example, I create a protocol Factory. I want to tell this factory that its job is to build QOTD protocol instances, so I set its protocol attribute to the QOTD class. Then, I want to listen on a TCP port, so I make a TCP4ServerEndpoint to identify the port that I want to bind to, and then pass the factory I just created to its listen method. You can stop the reactor by hitting Control-C in a terminal or calling reactor.stop.
!