Twisted several core components protocol,transport,factory,defer,reactor, the key components to clear up, it is twisted to get started, The approximate relationship is that the message loop is formed by the reactor (similar to the message loop mechanism of Windows), and when the socket is completed, it is called by defer (delay notification technology, which is based on the event driver) to invoke the corresponding response function to implement the asynchronous operation. Twisted's calling framework will first find a factory that listens (or connects, if it is a client) and constructs the appropriate protocol based on the factory interface Buildprotocol. In fact, the most necessary is to understand and study the Twisted.internet interfaces module, where the module explains all the components of the interface (these interfaces are derived from the Zope.inteferace), the following see twisted.internet.interfaces i Protocolfactory,itransport,iprotocol Interface Class
Class Iprotocolfactory (Interface): "" "Interface for protocol factories. "" "Def Buildprotocol (addr):" "" Called when a connection have been established to addr. If None is returned, the connection are assumed to has been refused, and the Port would close the connection. @type Addr: (host, port) @param addr:the Address of the newly-established connection @return: None if the Connection was refused, otherwise an object providing L{iprotocol}. "" "Def Dostart ():" "" called every time this is connected to a Port or Connector. "" "Def Dostop ():" "" called every time this is unconnected from a Port or Connector. "" "Class Itransport (Interface):" "" I am a Transport for bytes. I represent (and wrap) The physical connection and synchronicity of the framework which are talking to the network. I make no representations about whether calls to me would haPpen immediately or require returning to a control loop, or whether they would happen in the same or another thread. Consider methods of this class (aside from Getpeer) to being ' thrown over the wall ', to happen at some indeterminate t Ime.class Iprotocol (Interface): def datareceived (data): "" "called Whenever data is received. Use the This method to translate to a higher-level message. Usually, some callback'll be a made upon the receipt of each complete protocol message. @param data:a string of indeterminate length. Keep in mind so you'll probably need to buffer some data, as partial (or multiple) Protoc OL messages May received! I recommend that unit tests for protocols call through to this method with differing chunk sizes, do WN to one byte at a time. "" "Def connectionlost (reason):" "Called when the connection was shut down. Clear any CirculAR references here, and any external references to this Protocol. The connection has been closed. The C{reason} Failure wraps a l{twisted.internet.error.connectiondone} or L{twisted.internet.error.connectio Nlost} instance (or a subclass of one of those). @type reason:l{twisted.python.failure.failure} "" "Def MakeConnection (transport):" "" Make a Conn Ection to a transport and a server. "" "Def Connectionmade ():" "Called when a connection is made. This could be considered the initializer of the Protocol, because it was called when the connection was completed. For clients, the called once the connection to the server have been established; For servers, the called after an accept () call stops blocking and a socket have been received. If you need to send any greeting or initial a message, do it here. """
This provides the core interface for all components.
Here's a look at the example code I wrote
echo_client.py
From Twisted.internet.protocol import protocol, Clientfactoryfrom twisted.internet.endpoints import Clientfromstringfrom twisted.internet Import Reactorclass echoclientprotocol (Protocol):d ef connectionmade (self): Self.transport.write (' > To Server:hello Server ');d ef datareceived (self, data):p rint (' > from server:%s '% data) Reactor.stop () class Echoclientfactory (clientfactory):p Rotocol = echoclientprotocolif __name__ = = ' __main__ ': # Construct client Endpointsfor I in Xrange (Ten): Clientfromstring (reactor, ' tcp:localhost:8888 '). Connect ( Echoclientfactory ()) Reactor.run ()
echo_server.py
From Twisted.internet.protocol import protocol,factoryfrom twisted.internet import Reactorfrom Twisted.internet.endpoints Import Serverfromstringclass echoserverprotocol (Protocol):d ef connectionmade (self): Print (' > New connection made,from client! ') Self.factory.conn = Self.factory.conn + 1print (' > Now conn=%d '% self.factory.conn) def datareceived (self, data):p rint (' > Data from client:%s '% data) self.transport.write (' >host: ', repr (Self.transport.getHost ())) print (' >peer: ', repr (Self.transport.getPeer ())) #Close connection with Clientself.transport.loseConnection () Self.factory.conn = Self.factory.conn-1class echoserverfactory (factory):p Rotocol = Echoserverprotocoldef __init__ ( Self): Self.conn = 0if __name__ = = ' __main__ ': serverfromstring (reactor, ' tcp:8888 '). Listen (Echoserverfactory ()) Reactor.run ()
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Twisted Learning 01-echo server and Echo client