天天看點

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。

Python網絡程式設計Twisted架構學習(三)、關于defered

下面是一個加入了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六十多頁百度文庫最詳細的講解,由淺入深