链接延迟回调

时间:2013-08-15 00:52:03

标签: python twisted deferred asynchronous-messaging-protocol

我正在尝试在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)

服务器:

from twisted.internet.protocol import Factory
from twisted.protocols.amp import AMP

import commands

class CommandProtocol(AMP):

    def connect(self, username):
        print "Received connect command: %s." % (username)
        return {}
    commands.Connect.responder(connect)

    def say(self, phrase):
        print "Received phrase \"%s\"." % phrase
        return {}
    commands.Say.responder(say)

def main(port):
    factory = Factory()
    factory.protocol = CommandProtocol
    reactor.listenTCP(port, factory)
    print 'Started AMP server on port %d...' % port
    reactor.run()

main(12345)

仅在服务器端触发connect()

1 个答案:

答案 0 :(得分:1)

首先,启用日志记录:

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

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

其次,至少有一个最终的错误记录,记录Deferred上的未处理的失败,因此这些错误将显示出来而不是依赖于垃圾收集器:

from twisted.python.log import err

...

    d.addCallback(connect)
    d.addCallback(say)
    d.addErrback(err, "connect_protocol encountered some problem")

最后,延迟的结果会被附加到它的回调和错误更改。在这种情况下,传递给say的参数是Deferred返回的connect的结果。这与connect的参数不同,因此您不太可能在其上使用callRemote

您可以通过多种方式解决此问题。涉及最小代码更改(但不一定是最佳解决方案)的一种方法是将协议作为connect Deferred的结果中的额外值传递:

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

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