因此,主要问题是限制连接数。这实际上取决于您要使用的协议。假设,您将LineOnlyReceiver
其用作基本协议(其他继承者的Prototol
行为方式相同,但例如,AMP
情况会有所不同):
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