Search code examples
python-2.7servertwisted

Run something when first client connects in twisted?


So I have a main server written in twisted. I want to run a backup server on a different port when the first client connects. This behavior shouldn't repeat when the second client connects. Also the backup server should be closed when the last client disconnects.
How can I implement this behavior? Currently I am running a batch file before the reactor starts running. But the issue is that this would spawn an infinite loop. But I pass an argument that can stop it. However this means that when the main server goes down and the backup server is accepting clients then there are backup servers left.


Solution

  • You need to hook the connectionMade and connectionLost events of your twisted protocol. Inside these, you can implement your business logic.

    Take a look at the following events:

    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()
    

    You can test this server with telnet:

    telnet 127.0.0.1 1520