[Twisted-Python] Not understanding buildProtocol(), any clarification?

exarkun at twistedmatrix.com exarkun at twistedmatrix.com
Wed Sep 30 14:34:40 MDT 2009


On 08:16 pm, cyclops at speakeasy.net wrote:
>Hello, I'm trying to understand and use buildProtocol(), which isn't
>working as I expected, in two ways :) Question 1. If I have, on the
>Server side:
>
>class MyFactory(Factory):
>         protocol = MyTestProtocol
>         def buildProtocol(self, addr):
>                 p = Factory.buildProtocol(self, addr)
>                 p.transport.write('connected.\n')
>                 return p
>
>Should this work? Would the write() function execute? I thought that
>'p' was a fully usable Protocol object at that point, but Python
>disagrees with me :) Tells me it's a 'Nonetype' with no write()
>method. If I take out the write(), everything works fine, I can
>communicate between client/server, so no problems in the rest of the 
>code.

Nope.  There's no transport in buildProtocol.  That happens later.  You 
have to wait until "connectionMade" is called on the protocol before you 
trying to use the transport.
>
>Question 2. If I use buildProtocol() on the Server side to *not* make
>a connection, as:
>
>class MyFactory(Factory):
>         protocol = MyTestProtocol
>         def buildProtocol(self, addr):
>                 if (some condition):
>                         return Factory.buildProtocol(self, addr)
>                 else:
>                         return None
>
>What is supposed to happen on the Client Side when I return None? I
>was thinking that my factory's clientConnectionFailed() would fire,
>indicating that the Server refused a connection.
>
>Instead, what I get is my Client's connectionMade() firing,
>immediately followed by a clientConnectionLost() firing, as if the
>connection was made then dropped.

As you observed, doing this on the server accepts and then immediately 
closes the connection.  There is no way to not accept the connection. 
This is a limitation of the underlying platform APIs.

Jean-Paul




More information about the Twisted-Python mailing list