[Twisted-Python] at what point does reactor.run() need to be called?

Damon Fasching damon.fasching at sbcglobal.net
Tue Apr 6 00:39:57 MDT 2004


The following two modules work fine together.

# ================= server.py ====================
from twisted.spread import pb
from twisted.internet import reactor

class ServerClass(pb.Root):
    def remote_shutdown(self):
        print "server stopping"
        reactor.stop()

reactor.listenTCP(8789,
pb.PBServerFactory(ServerClass()))
reactor.run()

# =========== client.py =============
from twisted.spread import pb
from twisted.internet import reactor

def gotRootObject(obj):
    d = obj.callRemote("shutdown")
    d.addCallback(serverStopped)
    d.addErrback(remoteCallFailure)

def serverStopped(result):
    print 'server stopped'
    stop()

def remoteCallFailure(reason):
    print "remote call failed: %s" % (reason.value)
    stop()

def stop():
    print "client stopping"
    reactor.stop()

factory = pb.PBClientFactory()
reactor.connectTCP("localhost", 8789, factory)
d = factory.getRootObject()
d.addCallback(gotRootObject)
d.addErrback(remoteCallFailure, "getRootObject")
reactor.run()

==================================

If the last lines of client.py are modified as
follows, everything it still works.

dfactory = pb.PBClientFactory()
reactor.connectTCP("localhost", 8789, factory)
d = factory.getRootObject()
d.addCallback(gotRootObject)
reactor.run()
d.addErrback(remoteCallFailure, "getRootObject")

=======================================

However, if the call to reactor.run() is moved any
higher in client.py, the client seems to hang.  For
example, the following modification breaks it.

dfactory = pb.PBClientFactory()
reactor.connectTCP("localhost", 8789, factory)
d = factory.getRootObject()
reactor.run()
d.addCallback(gotRootObject)
d.addErrback(remoteCallFailure, "getRootObject")

=============================================

Is there an obvious reason for this that I'm missing? 
I would like to be able to dynamically connect to new
servers after starting my application and intereacting
with other servers, and so after already having called
reactor.run().  Can I do this?  I'm sure it is
possible.  But the quick test above makes it seem that
I have to invoke getRootObject() AND attach a callback
to the returned deferred before I can invoke
reactor.run().

Thanks,
  Damon





More information about the Twisted-Python mailing list