有人可以解释以下之间的区别吗。我真的很难掌握延迟概念,我以为我已经拥有它,因为我整天都在做例子。但我认为我必须是盲目的代码。我确信它非常简单。
这很有效。
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()
答案 0 :(得分:2)
您的工作和损坏示例之间的区别在于lambda
表达式隐式返回其结果。它的结果是Deferred
,这意味着链中的下一个回调将等待执行,直到其结果可用。
如果您更改add_numbers
的定义以返回callRemote
的结果,请执行以下操作:
def add_numbers(obj, a, b):
return obj.callRemote("add_numbers", a, b)
然后你破碎的例子将重新开始工作。