[Twisted-Python] help needed with flow-control for push protocol

exarkun at twistedmatrix.com exarkun at twistedmatrix.com
Thu Nov 5 15:42:12 EST 2009

On 05:52 pm, piemail at tiscali.it wrote:
>I need assistance figuring out how to create a push protocol that 
>flow control.
>To keep things simple, I'm trying to build a push-based echo server. 
>(1) accept incoming tcp connections
>(2) on each connection, all data rec'd should be echo'd unchanged.
>(3) should the output transport request that transmission be "paused,"
>the input transport (in this case, the same socket) should be similarly
>This would seem to be a simple problem.  I think my "PushEcho" class
>should implement both IConsumer and IProducer interfaces;

It doesn't need to implement IConsumer.  Protocols are hooked up to 
transports via the protocol's dataReceived method.  The protocol does 
not also need to be an IConsumer implementation with a write method.
>As a consumer,
>its dataRecieved method would cause it to act like a producer and call
>the transport's dataReceived method.

TCP transports, on the other hand, are IConsumer implementations.  So 
you meant the transport's write method (it has no dataReceived method). 
So, yes, the protocol should pass all data it receives back to the 
>Similarly, as a producer, it's
>pause, and resume methods would be called, and they would (as a
>consumer) just call the same functions in the transport.

This sounds right.
>However, I can't get the plumbing right.
>Can someone help by providing pointers or some sample code?

Here's some untested code:

    class SmartEcho(Protocol):

        def pauseProducing(self):

        def resumeProducing(self):

        def stopProducing(self):

        def connectionMade(self):
            self.transport.registerProducer(self, True)

        def dataReceived(self, bytes):

A careful examination of this code should also reveal the fact that it 
can be shortened to a more obscure form:

    class SmartEcho(Protocol):
        def connectionMade(self):
            self.transport.registerProducer(self.transport, True)

        def dataReceived(self, bytes):

Hope this helps,

More information about the Twisted-Python mailing list