运行 第一个客户端连接时发生扭曲?

Run something when first client connects in twisted?

所以我有一个用 twisted 编写的主服务器。当第一个客户端连接时,我想 运行 在不同端口上的备份服务器。当第二个客户端连接时,不应重复此行为。 当最后一个客户端断开连接时,备份服务器也应该关闭。
我怎样才能实现这种行为? 目前我正在 运行ning 一个批处理文件,然后反应器开始 运行ning。但问题是这会产生无限循环。但我通过了一个可以阻止它的论点。然而,这意味着当主服务器出现故障而备用服务器正在接受客户端时,还有备用服务器。

您需要挂钩您的扭曲协议的 connectionMadeconnectionLost 事件。在这些里面,您可以实现您的业务逻辑。

看看以下事件:

from twisted.internet.protocol import Factory
from twisted.protocols.basic import LineReceiver
from twisted.internet import reactor


class Protocol(LineReceiver):

    def __init__(self, factory):
        self.factory = factory

    def connectionMade(self):
        self.factory.clients.add(self)
        print('Client added. count:', len(self.factory.clients))

    def connectionLost(self, reason):
        self.factory.clients.remove(self)
        print('Client removed. count:', len(self.factory.clients))

    def lineReceived(self, line):
        self.transport.write(line)


class MyFactory(Factory):

    def __init__(self):
        self.clients = set()

    def buildProtocol(self, addr):
        return Protocol(self)


reactor.listenTCP(1520, MyFactory())
reactor.run()

您可以使用 telnet 测试此服务器:

telnet 127.0.0.1 1520