0

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.

1 Answers1

0

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
Yannic Hamann
  • 4,655
  • 32
  • 50
  • I got it working for the most part. One final question, once the server at 1520 stops running how do I make the client connect connect to the new server which i am starting at 1521. I am making use of the connectionLost() method on the client code, within which i call self.makeConnection(1521) this triggers the callback connectionMade() but in the next instant it triggers clientConnectionLost method in twisted.internet.protocol.ClientFactory. How do I make the new connection persist? – Piyush Divyanakar Oct 03 '17 at 05:50
  • Create a new question with your existing code. That would be much easier to support you. – Yannic Hamann Oct 03 '17 at 07:47
  • 1
    https://stackoverflow.com/questions/46538287/reconnect-to-different-address-in-twisted – Piyush Divyanakar Oct 03 '17 at 07:51