Python网络编程Twisted框架学习(三)、关于defered

  除了反应器 reactor 之外, Deferred 可能是最有用的 Twisted 对象。你可能在 Twisted 程序中 多次用到 Deferred , 所有有必要了解它是如何工作的。 Deferred 可能在开始的时候引起困惑, 但是它的目的是简单的:保持对非同步活动的跟踪,并且获得活动结束时的结果。
   Deferred 可以按照这种方式说明:可能你在饭店中遇到过这个问题, 如果你在等待自己喜欢 的桌子时, 在一旁哼哼小曲。 带个寻呼机是个好主意, 它可以让你在等待的时候不至于孤零 零的站在那里而感到无聊。你可以在这段时间出去走走,到隔壁买点东西。当桌子可用时, 寻呼机响了,这时你就可以回到饭店去你的位置了。
   一个 Deferred 类似于这个寻呼机。 它提供了让程序查找非同步任务完成的一种方式, 而在这 时还可以做其他事情。 当函数返回一个 Deferred 对象时, 说明获得结果之前还需要一定时间。 为了在任务完成时获得结果,可以为 Deferred 指定一个事件处理器。

最简单的Deferred程序:

from twisted.internet.defer import Deferred
def hello1(res):
    print(res)
    print('调用函数1')
def hello2(res):
    print(res)
    print('调用函数2')
d=Deferred()
d.addCallbacks(hello1,hello2)
d.callback('test')

d.addCallbacks(success,failure)成功的时候调用hello1,失败了调用hello2。
在这里插入图片描述

下面是一个加入了deferred的客户端程序。

from twisted.internet import reactor,defer,protocol 
class CallbackAndDisconnectProtocol(protocol.Protocol): 
    def connectionMade(self): 
        self.factory.deferred.callback("Connected!") 
        self.transport.loseConnection()
class ConnectionTestFactory(protocol.ClientFactory): 
    protocol=CallbackAndDisconnectProtocol 
    def __init__(self): 
        self.deferred=defer.Deferred() 
    def clientConnectionFailed(self,connector,reason): 
        self.deferred.errback(reason) 
def testConnect(host,port): 
    testFactory=ConnectionTestFactory() 
    reactor.connectTCP(host,port,testFactory) 
    return testFactory.deferred 
def handleSuccess(result,port): 
    print ("Connect to port %i"%port )
    reactor.stop() 
def handleFailure(failure,port): 
    print ("Error connecting to port %i: %s"%( port,failure.getErrorMessage())) 
    reactor.stop()
host='127.0.0.1'
port=51234
connecting=testConnect(host,port) 
connecting.addCallback(handleSuccess,port) 
connecting.addErrback(handleFailure,port) 
reactor.run()

当执行reactor.stop()的时候程序会继续执行完毕,大循环不再执行。Deferred日后应该会用到,还需多学习。




下面是这几天学习Twisted的一些资源:

https://blog.csdn.net/bluehawksky/article/details/79814577有关于回调的一些图解

http://blog.sina.com.cn/s/blog_704b6af70100py9n.html twisted书籍章节,基于github的一个诗歌项目

https://www.cnblogs.com/zhangjing0502/archive/2012/05/17/2506687.html
对protrocl,factory,reactor的讲解非常详细

http://blog.sina.com.cn/s/blog_704b6af70100py9n.html六十多页百度文库最详细的讲解,由浅入深

发布了50 篇原创文章 · 获赞 67 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_41033366/article/details/104200005
今日推荐