在 Twisted 中访问协议传输的正确方法是什么? [英] What is the correct way to access a protocols transport in Twisted?

查看:27
本文介绍了在 Twisted 中访问协议传输的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 TCP 客户端示例中:

In the TCP client example:

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()

我有一个需要向服务器发送数据的周期性任务.任务的所有逻辑都在协议和工厂之外.传递 f 并使用 f.protocol.transport.write("Something?") 是不好的形式吗?

I have a periodic task that needs to send data to the server. All the logic for the task is outside the Protocol and Factory. Is it bad form to pass around f and use f.protocol.transport.write("Something?")?

推荐答案

您可以重构您的代码并利用一些新的 API 来避免必须在工厂中做额外的工作来实现您的目标.Mike Lutz 的回答是完全正确的,也是我在端点之前向人们提出的建议.现在我们有了端点,我建议人们改用它们.

You can restructure your code and take advantage of some new-ish APIs to avoid having to do extra work in the factory to accomplish your goals. Mike Lutz's answer is perfectly correct and what I used to suggest to people before endpoints. Now that we have endpoints, I suggest that people use those instead.

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

The endpoint APIs let you write a main function that looks more like this:

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,它将为您处理一些反应堆簿记.

You might also consider adapting this to use twisted.internet.task.react which will take care of some of the reactor bookkeeping for you.

这篇关于在 Twisted 中访问协议传输的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆