链接延迟回调

2024-05-18 12:04:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试在AMP客户机中链接延迟,如下所示:

客户:

from twisted.internet.endpoints import TCP4ClientEndpoint, connectProtocol
from twisted.protocols.amp import AMP

import commands

def connect_protocol(host, port):
    destination = TCP4ClientEndpoint(reactor, host, port)
    d = connectProtocol(destination, AMP())

    def connect(protocol):
        print 'Connecting to server as Mr Spaceman...'
        return protocol.callRemote(commands.Connect,
                                   username='Mr Foo')

    def say(protocol):
        print 'Saying "Hello world" to the server...'
        return protocol.callRemote(commands.Say,
                                   phrase='Hello world')

    d.addCallback(connect)
    d.addCallback(say)


def main(host, port):
    connect_protocol(host, port)
    print 'Connected to %s:%d...' % (host, port)
    reactor.run()

main('127.0.0.1', 12345)

服务器:

^{pr2}$

只有connect()在服务器端被激发


Tags: tofromimporthostportdefconnecttwisted
1条回答
网友
1楼 · 发布于 2024-05-18 12:04:18

首先,启用日志记录:

from sys import stdout
from twisted.python.log import startLogging
startLogging(stdout)

现在你将看到程序中发生了什么。在

第二,至少有一个最终的错误回复,它记录Deferred上未处理的故障,因此这些故障将以确定的方式显示,而不是取决于垃圾收集器:

^{pr2}$

最后,Deferred的结果由附加到它的回调和errbacks更改。在本例中,传递给say的参数是connect返回的Deferred的结果。这与connect的参数不同,因此不太可能对其使用callRemote。在

你可以用很多不同的方法来解决这个问题。一种涉及到最少代码更改的方法(但不一定是最佳解决方案)是在connectDeferred的结果中传递协议:

^{3}$

相关问题 更多 >