在Twisted中访问协议传输的正确方法是什么?

时间:2014-04-27 22:31:20

标签: python twisted

在TCP客户端示例中:

from twisted.internet import reactor, protocol


# a client protocol

class EchoClient(protocol.Protocol):
    """Once connected, send a message, then print the result."""

    def connectionMade(self):
        self.transport.write("hello, world!")

    def dataReceived(self, data):
        "As soon as any data is received, write it back."
        print "Server said:", data
        self.transport.loseConnection()

    def connectionLost(self, reason):
        print "connection lost"

class EchoFactory(protocol.ClientFactory):
    protocol = EchoClient

    def clientConnectionFailed(self, connector, reason):
        print "Connection failed - goodbye!"
        reactor.stop()

    def clientConnectionLost(self, connector, reason):
        print "Connection lost - goodbye!"
        reactor.stop()


# this connects the protocol to a server runing on port 8000
def main():
    f = EchoFactory()
    reactor.connectTCP("localhost", 8000, f)
    reactor.run()

# this only runs if the module was *not* imported
if __name__ == '__main__':
    main()

我有一个需要将数据发送到服务器的定期任务。该任务的所有逻辑都在Protocol和Factory之外。传递f并使用f.protocol.transport.write("Something?")是不好的形式?

2 个答案:

答案 0 :(得分:2)

您可以重新构建代码并利用一些新的API来避免在工厂中进行额外的工作以实现目标。 Mike Lutz的答案是完全正确的,我曾经在终点之前向人们建议。既然我们有端点,我建议人们使用端点。

端点API允许您编写一个看起来更像这样的主函数:

def main():
    e = HostnameEndpoint(reactor, "localhost", 8000)
    f = EchoFactory()
    d = e.connect(f)
    d.addCallback(connected)
    return d

def connected(protocol):
    # protocol is an instance of EchoClient and is connected
    return LoopingCall(doStuff, protocol).start(3)

您也可以考虑使用twisted.internet.task.react进行调整,以便为您处理一些反应堆簿记。

答案 1 :(得分:0)

我也是Twisted世界的新人,所以请带上一粒盐,但我说它是可接受的形式。

请参阅以下内容,我举例说明如何将扭曲的部分挂钩:Persistent connections in twisted。 (因为碰巧答案也谈到了周期性任务......)

修改

哎呀,等等。你在那里有一家工厂。

工厂每次连接时都会生成协议的新实例,因此f.protocol.transport.write将不起作用(protocol将指向类,而不是连接的实例班级)。尝试从Persistent connections问题运行我的代码示例,我创建一个连接列表(工厂中的self.clients),使用该结构,您可以通过迭代来使用各种连接的.write连接列表