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

exarkun at twistedmatrix.com exarkun at twistedmatrix.com
Thu Nov 5 13:42:12 MST 2009


On 05:52 pm, piemail at tiscali.it wrote:
>Hi,
>
>I need assistance figuring out how to create a push protocol that 
>implements
>flow control.
>
>To keep things simple, I'm trying to build a push-based echo server. 
>It
>should
>(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
>blocked.
>
>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 
transport.
>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):
        implements(IProducer)

        def pauseProducing(self):
            self.transport.pauseProducing()

        def resumeProducing(self):
            self.transport.resumeProducing()

        def stopProducing(self):
            self.transport.stopProducing()

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

        def dataReceived(self, bytes):
            self.transport.write(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):
            self.transport.write(bytes)

Hope this helps,
Jean-Paul




More information about the Twisted-Python mailing list