有人可以解释以下之间的区别。我真的很难掌握 Deferred 的概念,我以为我已经掌握了它,因为我整天都在做例子。但我想我一定是代码盲。我敢肯定它真的很简单。
这行得通。
from twisted.spread import pb
from twisted.internet import reactor
from twisted.python import util
if __name__ == '__main__':
def print_result(result):
print result
def add_numbers(obj, a, b):
obj.callRemote("add_numbers", a, b)
factory = pb.PBClientFactory()
reactor.connectTCP("localhost", 8789, factory)
d = factory.getRootObject()
d.addCallback(lambda object: object.callRemote("add_numbers", 1, 2))
d.addErrback(lambda reason: 'error: '+str(reason.value))
d.addCallback(print_result)
d.addErrback(lambda reason: 'error: '+str(reason.value))
d.addCallback(lambda _: reactor.stop())
d = factory.getRootObject()
reactor.run()
而这并没有
from twisted.spread import pb
from twisted.internet import reactor
from twisted.python import util
if __name__ == '__main__':
def print_result(result):
print result
def add_numbers(obj, a, b):
obj.callRemote("add_numbers", a, b)
factory = pb.PBClientFactory()
reactor.connectTCP("localhost", 8789, factory)
d = factory.getRootObject()
d.addCallback(add_numbers, 1, 2)
d.addErrback(lambda reason: 'error: '+str(reason.value))
d.addCallback(print_result)
d.addErrback(lambda reason: 'error: '+str(reason.value))
d.addCallback(lambda _: reactor.stop())
d = factory.getRootObject()
reactor.run()
我一生都无法弄清楚为什么它会因以下错误而崩溃:
Unhandled error in Deferred:
Unhandled Error
Traceback (most recent call last):
Failure: twisted.spread.pb.PBConnectionLost: [Failure instance: Traceback (failure with no frames): <class 'twisted.internet.error.ConnectionLost'>: Connection to the other side was lost in a non-clean fashion: Connection lost.
]
服务器端代码是
from twisted.spread import pb
from twisted.internet import reactor
class Echoer(pb.Root):
def remote_echo(self, st):
print 'echoing:', st
return st
def remote_add_numbers(self, a, b):
print 'adding:', a, b
c = a + b
return c
if __name__ == '__main__':
reactor.listenTCP(8789, pb.PBServerFactory(Echoer()))
reactor.run()