deferred “异步”功能的实现,与多线程完全不同,具有以下特点:1. deferred 产生的 event,是函数调用返回的对象;2. deferred 代表一个连接任务,负责报告任务执行的延迟情况和最终结果;3. 对deferred 的操作,通过预定的“事件响应器”(event handler)进行。defer的使用方式:1). 在factory中创建deferred对象,但在调用factory对象之外返回自身的deferred对象,然后再添加callback和errback, 具体示例如下:#! /usr/bin/env python#coding=utf-8from twisted.internet import reactor, defer, protocolclass 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( port): testFactory = ConnectionTestFactory() reactor.listenTCP(port, testFactory) return testFactory.deferreddef handleSuccess(result, port): #deferred "event-responsor": handle finished connection print 'result-----',result print "Connected to port %i" % port # reactor.stop()def handleFailure(failure, port): print "Error connecting to port %i: %s" % (port, failure.getErrorMessage()) # reactor.stop()if __name__ == '__main__': port = 50001 conndefer = testConnect(port) conndefer.addCallback(handleSuccess, port) conndefer.addErrback(handleFailure, port) reactor.run()2). 不显示创建deferred对象, 在函数返回时,我们调用defer.succeed(results)函数。其中result则可以为调用我们延时操作函数返回的结果。示例如下:#! /usr/bin/env python#coding=utf-8from twisted.internet import protocol, reactor, deferfrom twisted.protocols import basicclass FingerProtocol(basic.LineReceiver): def lineReceived(self, user): self.factory.getUser(user ).addErrback(lambda _: "Internal error in server" ).addCallback(lambda m: (self.transport.write(m+"/r/n")))class FingerFactory(protocol.ServerFactory): protocol = FingerProtocol def __init__(self, **kwargs): self.users = kwargs print self.users def getUser(self, user): return defer.succeed(self.users.get(user, "No such user"))if __name__ == '__main__': reactor.listenTCP(1077, FingerFactory(hd='Hello my python world')) reactor.run()