So, the main problem is to limit the number of connections. This is really depends on the protocol you would like to use. Let's assume, you use LineOnlyReceiver
as a base protocol (other inheritors of Prototol
will behave the same way, but, for example, AMP
will be a bit different case):
from twisted.internet.protocol import ServerFactory
from twisted.protocols.basic import LineOnlyReceiver
class NoConnectionSlots(Exception):
message = "Sorry, bro. There are no free slots for you. Try again later."
class ExampleProtocol(LineOnlyReceiver):
def connectionMade(self):
try:
self.factory.client_connected(self)
except NoConnectionSlots as e:
self.sendLine("{:}\\n".format(unicode(e)))
self.transport.loseConnection()
def connectionLost(self, reason):
self.factory.client_left(self)
class ExampleServerFactory(ServerFactory):
protocol = ExampleProtocol
max_connections = 10
def __init__(self):
self._connections = []
def client_connected(self, connection):
if len(self._connections) < self.max_connections:
raise NoConnectionSlots()
self._connections.append(connection)
def client_left(self, connection):
try:
self._connections.remove(connection)
except ValueError as e:
pass # place for logging