python - Twisted callback loop blocking further data from being recieved -
when callback loop running in twisted, impression reactor still able send/receive data server, able function 'between' callbacks. however, when run script below, entirely ignores self.transport.write()
line. server basic echo server twisted have on website.
from twisted.internet import reactor, protocol twisted.internet.defer import deferred class echoclient(protocol.protocol): deferred = deferred() def connectionmade(self): self.deferred.addcallback(self.dothing) self.deferred.callback(0) def dothing(self, _): print 'xxx' self.transport.write('hello, world!') self.deferred.addcallback(self.dothing) def datareceived(self, data): "as data received, write back." print "server said:", data self.transport.loseconnection() class echofactory(protocol.clientfactory): protocol = echoclient def main(): f = echofactory() reactor.connecttcp('192.168.0.7', 8000, f) # correctly connected server reactor.run() if __name__ == '__main__': main()
i expected one, or few, 'xxx's being printed, server sending echo of 'hello, world!' me, more 'xxx's. instead infinite scrolling of 'xxx's , no attempt @ sending 'hello, world!' server. missing/misunderstanding?
the problem example never letting main loop run.
when connection established, add callback self.deferred
- i'm not sure operation self.deferred
supposed represent, apparently nothing useful.
then (synchronously) call self.deferred
. goes right away execute dothing
, calls self.transport.write
. adds bytes outgoing buffer sent when mainloop next runs. then, in callback, (synchronously) add callback self.deferred
run current callback completed. go dothing
, calls self.transport.write
. still haven't written yet, let alone read deliver datareceived
, because haven't made main loop. add callback deferred
. calls dothing
again.
this keeps going forever, allocating infinite amount of memory on transport buffer ever-increasing amount of outgoing traffic, never allow program return connectionmade
, make main loop, , wait writability , readability events.
i don't know how fix program because it's not clear you're trying do, whatever is, isn't how :).
Comments
Post a Comment