Twisted Python 工厂方法在使用反应器包装器时未被调用

Twisted Python factory methods aren't getting called when using reactor wrappers

我有一个简单的客户端/服务器设置。这是客户端代码:

from twisted.internet import reactor
from twisted.internet import protocol
from twisted.internet.endpoints import TCP4ClientEndpoint

class MyProtocol(protocol.Protocol):

    def connectionMade(self):
        print "Hello!"

    def dataReceived(self, data):
        print data

class MyProtocolFactory(protocol.ClientFactory):

    def startedConnecting(self, connector):
        print "Starting to connect!"

    def buildProtocol(self, addr):
        return MyProtocol()

    def clientConnectionLost(self, connector, reason):
        print "Lost connection, reason = %s" % reason

    def clientConnectionFailed(self, connector, reason):
        print "Connection failed, reason = %s" % reason
        reactor.stop()

endpoint = TCP4ClientEndpoint(reactor, "127.0.0.1", 54321, timeout=5)
endpoint.connect(MyProtocolFactory())
reactor.run()

出于某种原因,此客户端将连接到服务器并且协议工作正常(我可以看到 "Hello!" 打印出来,以及成功连接后服务器发送的数据),但它不会调用任何协议工厂方法。 startedConnecting 不会被调用,如果我停止服务器,我也不会看到 clientConnectionLost 被调用。如果我在服务器启动之前尝试 运行 客户端,我也希望看到 clientConnectionFailed 被调用。

这是奇怪的部分...如果我将上面代码中的最后 3 行更改为以下内容:

reactor.connectTCP("127.0.0.1", 54321, MyProtocolFactory())
reactor.run()

然后一切都按预期工作,并且在上述所有情况下都会调用所有方法。

我对端点的理解是,它们用额外的行为包装 "connectTCP"(以及其他),但我不明白为什么它在第二个代码片段中起作用,但在第一个代码片段中不起作用。

有什么想法吗?

客户端端点接口不调用 ClientFactory 的额外连接状态通知方法。

因此,虽然端点在某种意义上确实如此 "wrap" connectTCP 等,但它们与使用那些较低级别的方法具有完全相同的行为是不正确的。

对于端点,工厂的工作是提供协议实例。工厂不再负责连接管理的其他方面。

补充我上面讨论的补充说明:

If you’ve used ClientFactory before, keep in mind that the connect method takes a Factory, not a ClientFactory. Even if you pass a ClientFactory to endpoint.connect, its clientConnectionFailed and clientConnectionLost methods will not be called. In particular, clients that extend ReconnectingClientFactory won’t reconnect. The next section describes how to set up reconnecting clients on endpoints.

来自此处找到的端点文档:http://twistedmatrix.com/documents/current/core/howto/endpoints.html