以扭曲协议定期运行功能

时间:2008-11-24 22:21:18

标签: python tcp twisted protocols

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

2 个答案:

答案 0 :(得分:38)

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

以下是一个完整的示例,说明如何将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()

答案 1 :(得分:3)

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

这感觉有点侵入性,但如果没有协议可以控制传输/接收,我认为你不想这样做。当然,我必须看到你的代码真的知道它是如何适合的。有github链接? :)