我正在寻找一种方法来定期通过连接到 TCP 端口的所有客户端发送一些数据。我正在看扭曲的Python,我知道reactor.callLater。但是我如何使用它定期向所有连接的客户端发送一些数据?数据发送逻辑位于Protocol类中,由反应器根据需要实例化。我不知道如何将它从反应堆绑定到所有协议实例......
您可能希望在工厂中执行此操作以进行连接。每次建立和丢失连接时,工厂不会自动收到通知,因此您可以通过协议通知它。
下面是一个完整的示例,说明如何将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()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)