我要寻找一种方法来在连接到TCP端口的所有客户端定期发送一些数据。我在看扭曲的蟒蛇,我知道reactor.callLater的。但我怎么用它来发送一些数据定期所有连接的客户端?数据发送逻辑是在协议类别,它是由反应器中根据需要实例化。我不知道如何从反应器比分扳成所有协议实例...

有帮助吗?

解决方案

您可能会想为连接做到这一点的工厂。工厂不自动通知的每一个连接并失去的时间,这样你就可以从协议通知了。

下面是如何结合使用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()

其他提示

我想像做到这一点的最简单方法是在客户端与connectionMade和connectionLost的协议来管理客户名单,然后使用LoopingCall要求每个客户端发送数据。

这感觉有点侵入性的,但我不认为你会想这样做,而不必在发送/接收一些控制协议。当然,我得看看你的代码,以真正懂得它会很好适应。有一个GitHub的链接? :)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top