【问题标题】:Running a function periodically in twisted protocol在扭曲协议中定期运行函数
【发布时间】:2023-03-12 19:37:01
【问题描述】:

我正在寻找一种通过连接到 TCP 端口的所有客户端定期发送一些数据的方法。我在看twisted python,我知道reactor.callLater。但是如何使用它定期向所有连接的客户端发送一些数据?数据发送逻辑在 Protocol 类中,由 reactor 按需实例化。我不知道如何将它从反应堆绑定到所有协议实例......

【问题讨论】:

    标签: python tcp twisted protocols


    【解决方案1】:

    您可能希望在工厂中为连接执行此操作。每次建立和丢失连接时不会自动通知工厂,因此您可以通过协议通知它。

    这是一个完整示例,说明如何将 twisted.internet.task.LoopingCall 与自定义的基本工厂和协议结合使用,以每 10 秒向每个连接宣布“已过去 10 秒”。

    from twisted.internet import reactor, protocol, task
    
    class MyProtocol(protocol.Protocol):
        def connectionMade(self):
            self.factory.clientConnectionMade(self)
        def connectionLost(self, reason):
            self.factory.clientConnectionLost(self)
    
    class MyFactory(protocol.Factory):
        protocol = MyProtocol
        def __init__(self):
            self.clients = []
            self.lc = task.LoopingCall(self.announce)
            self.lc.start(10)
    
        def announce(self):
            for client in self.clients:
                client.transport.write("10 seconds has passed\n")
    
        def clientConnectionMade(self, client):
            self.clients.append(client)
    
        def clientConnectionLost(self, client):
            self.clients.remove(client)
    
    myfactory = MyFactory()
    reactor.listenTCP(9000, myfactory)
    reactor.run()
    

    【讨论】:

    • 谢谢!这有很大帮助。我试图处理在协议类中发送数据并且在处理无法访问所有客户端时遇到问题(有一个单例类来保存它们!)!在工厂子类中这样做更有意义。我会重写我的代码...谢谢!
    • 如何编写测试来验证客户端是否在一分钟内获得“10 秒已过去\n”六次?
    【解决方案2】:

    我想最简单的方法是在客户端使用 connectionMade 和 connectionLost 管理协议中的客户端列表,然后使用 LoopingCall 要求每个客户端发送数据。

    这感觉有点侵入性,但我认为如果协议没有对传输/接收进行一些控制,您不会想要这样做。当然,我必须查看您的代码才能真正了解它如何适合。有github链接吗? :)

    【讨论】:

    • 我得到了初始版本。 reactor.callLater 可以在任何地方调用,所以我最终从 connectionMade() 调用它。然而,现在的问题是每个连接都有自己的计时器和数据。我真的很想要一个计时器和数据。 (如广播)...
    猜你喜欢
    • 1970-01-01
    • 2011-05-17
    • 2012-09-23
    • 1970-01-01
    • 1970-01-01
    • 2013-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多