트위스트 파이썬 네트워크 프로그래밍 학습 프레임 워크 (C), defered에

  원자로 원자로뿐만 아니라, 트위스트 아마도 가장 유용한 객체를 이연. 당신은 어떻게 작동하는지 이해하기 위해, 트위스트 프로그램에 필요한 모든를 이연 여러 번 사용할 수 있습니다. 이연은 처음에 혼란을 일으킬 수 있지만, 그 목적은 간단하다 : 비동기 이벤트를 추적하고, 결과는 이벤트의 끝에서 얻을.
   연기는 이런 방식으로 설명 : 당신이 측면 험 가곡에서 당신의 마음에 드는 테이블을 기다리고있는 경우, 레스토랑에서이 문제에 걸쳐 올 수 있습니다. 호출기를 가지고하는 것은 좋은 아이디어입니다, 당신이 혼자 서와 지루하지 않을 때 대기 할 수 있습니다. 뭔가를 구입하는 문 옆에 당신은이 시간에 산책을 갈 수 있습니다. 테이블을 사용할 수있는 경우, 호출기 울렸다는, 당신은 당신의 호텔 위치로 돌아갈 수 있습니다.
   이는 이연 호출기와 유사하다. 이 프로그램이 비동기 작업이 완료 찾을 수있는 방법을 제공하고,이 시간에 당신은 다른 일을 할 수있다. 함수가 지연된 객체를 반환 할 때 참고 또한 얻어진 결과 전에 약간의 시간이 걸릴. 이연에 대한 작업이 완료되면 결과를 얻기 위해서는 이벤트 핸들러를 지정할 수 있습니다.

가장 쉬운 이연 프로그램 :

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 성공적으로 호출 hello1가, 호출 hello2 실패 (성공, 실패).
그림 삽입 설명 여기

다음은 결합 된 연기 클라이언트 프로그램입니다.

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 () 프로그램이 완료 계속되면 싸이클이 실행되지 않습니다. 미래에 사용되어야한다 이연, 배울 필요가있다.




여기에 트위스트 이러한 일을 배울 수있는 일부 리소스는 다음과 같습니다

https://blog.csdn.net/bluehawksky/article/details/79814577 콜백에 대한 몇 가지 설명

http://blog.sina.com.cn/s/blog_704b6af70100py9n.html 시를 프로젝트의 GitHub의에 따라 트위스트 책 장,

https://www.cnblogs.com/zhangjing0502/archive/2012/05/17/2506687.html
아주 자세하게 protrocl, 공장, 반응기에 설명

http://blog.sina.com.cn/s/blog_704b6af70100py9n.html 가장 상세한 설명, 깊은의 육십 페이지 바이 라이브러리

게시 50 개 원래 기사 · 원 찬양 67 ·은 10000 +를 볼

추천

출처blog.csdn.net/weixin_41033366/article/details/104200005