[Twisted-web] HTTPClient vs. HTTPClientFactory

Matthew Glubb matt at madebykite.com
Fri Apr 18 03:26:39 EDT 2008

Hi Andrew,
On 18 Apr 2008, at 01:32, Andrew McNabb wrote:
> First, I think I understand the difference between protocol factories
> and protocols, but I could use a little reassurance.  My current
> understanding is that the protocol factory holds the state that is
> common to all connections, whereas the protocol holds the state  
> that is
> specific to a particular connection.  Is that an accurate  
> understanding?

No, this is not quite correct. In the case of a  
ServerProtocolFactory, you are right, there is one instance for your  
server, but it isn't responsible for managing state. New connections  
to your server will cause the reactor to call buildProtocol in your  
ServerFactory. This, in turn, will create one instance of your  
ServerProtocol for each new connection. It is the ServerProtocol that  
manages the state of that single connection. If you want to manage  
some kind of global state between connections, you should write a  
logic class that exists as a single, global instance within your  

> If that is correct, then what is the difference between a protocol
> factory and a protocol for a client (like HTTPClient) where only one
> connection is involved?  I'm a bit confused about why  
> HTTPClientFactory
> isn't a trivial class.  According to my current understanding, all of
> the logic would be in HTTPClient.

A ClientProtocolFactory instance is created for *every* client  
connection you attempt to create. The point here is that your  
ClientProtocol is not instantiated *until* the connection has been  
made to your remote resource. The ClientProtocolFactory manages the  
instantiation of your ClientProtocol when successfully connected. I  
agree that 'ClientProtocolFactory' is somewhat misleading as it  
indicates that it is possible to create more than one ClientProtocol  
from your factory. Within normal design patterns, this would be true,  
but in this case your ClientProtocolFactory will only ever create one  
instance of your ClientProtocol (unless you are doing something  
*really* funky - and probably bad!).

To sum up, you always create a new ClientProtocolFactory when making  
a new client connection:

reactor.connectTCP(host, port, ClientProtocolFactory()

Repeat for more clients...

Hope that helps,


More information about the Twisted-web mailing list