I have a twisted factory that builds a protocol from LineReceiver, listening to a TCP socket.
I wish to limit the number of client connections to the LineReceiver to 1 and have additional client requests 'refused'.
I have seen some other hints referring to how to make clients wait (How to limit the number of simultaneous connections in Twisted) but I would like the cleanly refuse any additional connections.
My code is a simplification taken from the previous URL on limiting simultaneous connections.
Do I need to refuse connections in the factory or build a protocol and then close the connection straight away?
EDIT: Aha. I think I solved it, in that when connections are received in the protocol, if buildCount > 1 then self.transport.abortConnection() seems to work
Any suggestions/comments on whether this is the right way to do it? Perhaps it would be nicer to have a 'connection refused' rather than the server accept the connection and then close it straight away.
class myProtocol(LineReceiver):
def __init__(self, factory):
self.factory = factory
def connectionMade(self):
if self.factory.buildCount > 1:
self.transport.abortConnection()
else:
self.sendLine("connection accepted".encode())
def connectionLost(self):
# decrement count of connected clients
self.factory.buildCount -= 1
def lineReceived(self, line):
self.sendLine("echo '{0}'".format(line.decode()).encode())
class myFactory(Factory):
def __init__(self, mode, logger):
"""
Factory only runs once
"""
self.buildCount = 0
def buildProtocol(self, addr):
"""
Factory runs buildProtocol for each connection
"""
self.buildCount += 1
return myProtocol(self)
reactor.listenTCP(9000, myFactory())
reactor.run()