谁能解释这段代码

Can anyone explain this code

有一个困惑,在下面的代码中 "gotProtocol" 被传递给回调 function.while 使用示例服务器程序执行它,它可以使用方法 [=14= 发送那些字符串] 我们在 class greeter 中注册的。但是如何?

from twisted.internet import reactor
from twisted.internet.protocol import Factory, Protocol
from twisted.internet.endpoints import TCP4ClientEndpoint

class Greeter(Protocol):
    def sendMessage(self, msg):
        self.transport.write("MESSAGE %s\n" % msg)

class GreeterFactory(Factory):
    def buildProtocol(self, addr):
        return Greeter()

def gotProtocol(p):
    p.sendMessage("Hello")
    reactor.callLater(1, p.sendMessage, "This is sent in a second")
    reactor.callLater(2, p.transport.loseConnection)

point = TCP4ClientEndpoint(reactor, "localhost", 1234)
d = point.connect(GreeterFactory())
d.addCallback(gotProtocol)
reactor.run()

它的异步编程。一开始可能有点混乱。基本思想是您定义函数并将它们传递给库,它会在需要时执行它们。

gotProtocol是一个回调函数。 addCallback 没有调用它,该函数作为参数传递并存储以备后用。

变量 p 表示当 twisted 调用您的独立函数时将传递的值 gotProtocol 并将提供函数上下文(即您将有一些操作)。

展示一个非常简单的例子

import time
# imagine this function is defined in a library
def libraryfunc(cb):
    time.sleep(1)
    cb(1)

# your callback function that will be called later by library
def mycb(i):
    print "the library returned me %d" % i

libraryfunc(mycb)

你向库传递一个函数,稍后它会通过调用该函数返回给你一些东西。

p 将是一个 Greeter 实例。由于 Greeter 继承自 Protocol 它可以被 polymorphically 用作内部的 Protocol 对象,但是当你收到它时你可以调用特定于 Greeter class sendMessage 以及从 Protocol 继承的方法,这些方法将完成网络工作,例如self.transport.write.

至于 Greeter 实例的创建方式和时间。您提供了一个 factory class that will return an instance of Greeter so twisted can create the instance when it needs to and return it to you in the callback. The advantage of the factory method is that twisted doesn't need to know the concrete class 它正在实例化,只要 class 继承自 Protocol 它是可用的。