【发布时间】:2023-03-12 19:37:01
【问题描述】:
我正在寻找一种通过连接到 TCP 端口的所有客户端定期发送一些数据的方法。我在看twisted python,我知道reactor.callLater。但是如何使用它定期向所有连接的客户端发送一些数据?数据发送逻辑在 Protocol 类中,由 reactor 按需实例化。我不知道如何将它从反应堆绑定到所有协议实例......
【问题讨论】:
标签: python tcp twisted protocols
我正在寻找一种通过连接到 TCP 端口的所有客户端定期发送一些数据的方法。我在看twisted python,我知道reactor.callLater。但是如何使用它定期向所有连接的客户端发送一些数据?数据发送逻辑在 Protocol 类中,由 reactor 按需实例化。我不知道如何将它从反应堆绑定到所有协议实例......
【问题讨论】:
标签: python tcp twisted protocols
您可能希望在工厂中为连接执行此操作。每次建立和丢失连接时不会自动通知工厂,因此您可以通过协议通知它。
这是一个完整示例,说明如何将 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链接吗? :)
【讨论】: