I have a server application written in python using twisted and I’d like to know how to kill instances of my protocol (bottalk). Everytime I get a new client connection, I see the instance in memory (print Factory.clients) .. but let’s say I want to kill one of those instances from the server side (drop a specific client connection)? Is this possible? I’ve tried looking for a phrase using lineReceived, then if it matches, self.transport.loseConnection(). But that doesn’t seem to reference the instance anymore or something..
class bottalk(LineReceiver):
from os import linesep as delimiter
def connectionMade(self):
Factory.clients.append(self)
print Factory.clients
def lineReceived(self, line):
for bots in Factory.clients[1:]:
bots.message(line)
if line == "killme":
self.transport.loseConnection()
def message(self, message):
self.transport.write(message + '\n')
class botfactory(Factory):
def buildProtocol(self, addr):
return bottalk()
Factory.clients = []
stdio.StandardIO(bottalk())
reactor.listenTCP(8123, botfactory())
reactor.run()
You closed the TCP connection by calling
loseConnection. But there’s no code anywhere in your application that removes items from theclientslist on the factory.Try adding this to your protocol:
This will remove the protocol instance from the
clientslist when the protocol’s connection is lost.Also, you should consider not using the global
Factory.clientsto implement this functionality. It’s bad for all the usual reasons globals are bad. Instead, give each protocol instance a reference to its factory and use that:Now each
bottalkinstance can useself.factory.clientsinstead ofFactory.clients.