Search code examples
pythontwistedtwisted.internet

How to count the number of currently connected Protocols in Python twisted framework


I was trying to count the number of active protocols in twisted but i got an error:

exceptions.AttributeError: Factory instance has no attribute 'numProtocols'

Below is the code:

class EchoPro(Protocol):
    def connectionMade(self):
        self.factory.numProtocols = self.factory.numProtocols+1
        if self.factory.numProtocols > 100:
            self.transport.write("Too many connections, try later")
            self.transport.loseConnection()
    def connectionLost(self, reason):
        self.factory.numProtocols = self.factory.numProtocols-1

    def dataReceived(self, data):
        self.transport.write(data)

Solution

  • That's because self.factory does not contain the numProtocols attribute.

    To customise the protocol's factory you create a Factory for your protocol by subclassing twisted.internet.protocol.Factory.

    Example:

    from twisted.internet.protocol import Protocol, Factory
    from twisted.internet import reactor
    
    class Echo(Protocol):
        # ... your implementation as it is now ...
    
    class EchoFactory(Factory):  # Factory for your protocol
        protocol = Echo
        numProtocols = 0
    
    factory = EchoFactory()
    factory.protocol = Echo
    
    reactor.listenTCP(8007, factory)
    reactor.run()
    

    Alternatively, you could just modify the factory instance once it is created, as done in the docs.

    Example:

    from twisted.internet.protocol import Protocol, Factory
    from twisted.internet import reactor
    
    class Echo(Protocol):
        # ... your implementation as it is now ...
    
    def getEchoFactory():
        factory = Factory()
        factory.protocol = Echo
        factory.numProtocols = 0
        return factory
    
    reactor.listenTCP(8007, getEchoFactory())
    reactor.run()