0

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()
  • Why scare quotes 'refused'? What is not "clean" about the other question/answer you linked to? – Jean-Paul Calderone Aug 30 '18 at 10:17
  • I'm not sure what you mean by "Why scare quotes 'refused'?" I essentially want additional clients that try to connect to be given 'connection refused'. The other answers I linked to, talk about giving the additional clients a DoNothing() protocol, which essentially lets them connect. – Kym Newbery Sep 07 '18 at 10:11

0 Answers0