how to kill twisted protocol instances python

a 夏天 提交于 2019-12-10 21:24:27

问题


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()

回答1:


You closed the TCP connection by calling loseConnection. But there's no code anywhere in your application that removes items from the clients list on the factory.

Try adding this to your protocol:

def connectionLost(self, reason):
    Factory.clients.remove(self)

This will remove the protocol instance from the clients list when the protocol's connection is lost.

Also, you should consider not using the global Factory.clients to 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:

class botfactory(Factory):

    def buildProtocol(self, addr):
        protocol = bottalk()
        protocol.factory = self
        return protocol

factory = botfactory()
factory.clients = []

StandardIO(factory.buildProtocol(None))

reactor.listenTCP(8123, factory)

Now each bottalk instance can use self.factory.clients instead of Factory.clients.



来源:https://stackoverflow.com/questions/13239244/how-to-kill-twisted-protocol-instances-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!