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.
Asked
Active
Viewed 72 times
0

Piyush Divyanakar
- 241
- 2
- 15
-
Could I help you with the answer? – Yannic Hamann Oct 02 '17 at 20:53
-
I am working on it. – Piyush Divyanakar Oct 03 '17 at 03:46
1 Answers
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
-
1https://stackoverflow.com/questions/46538287/reconnect-to-different-address-in-twisted – Piyush Divyanakar Oct 03 '17 at 07:51