【问题标题】:how to kill twisted protocol instances python如何杀死扭曲的协议实例python
【发布时间】:2012-11-06 06:01:24
【问题描述】:

我有一个使用twisted 用python 编写的服务器应用程序,我想知道如何杀死我的协议实例(bottalk)。每次我获得一个新的客户端连接时,我都会在内存中看到该实例(打印 Factory.clients).. 但是假设我想从服务器端杀死其中一个实例(删除特定的客户端连接)?这可能吗?我尝试使用 lineReceived 查找短语,如果匹配,则 self.transport.loseConnection()。但这似乎不再引用实例或其他东西..

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

【问题讨论】:

    标签: python twisted instance


    【解决方案1】:

    您通过调用 loseConnection 关闭了 TCP 连接。但是您的应用程序中没有任何代码可以从工厂的 clients 列表中删除项目。

    尝试将此添加到您的协议中:

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

    当协议的连接丢失时,这将从clients 列表中删除协议实例。

    此外,您应该考虑不使用全局 Factory.clients 来实现此功能。由于全局变量不好的所有常见原因,这很糟糕。相反,给每个协议实例一个对 its 工厂的引用并使用它:

    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)
    

    现在每个bottalk 实例都可以使用self.factory.clients 而不是Factory.clients

    【讨论】:

    • 无法编辑最后一条评论,所以这里是这条。我仍然坚持, l​​ostConnection() 不会关闭实例。我知道 lossConnection() 有效,至于测试我将其卡在 connectionMade() 中,并且所有新的客户端连接立即断开。但是,我仍然有如何告诉 lostConnection() 我要关闭哪个实例的问题。在它丢失连接()之后,你已经死去清理实例了,谢谢!但是我如何让 lostConnection() 在特定实例上工作?也感谢您的建议。我正在消化这个。
    • loseConnection 关闭由您调用它的传输实例表示的连接。 transport.loseConnection() 关闭由transport 表示的连接。 anotherTransport.loseConnection() 关闭由anotherTransport 表示的连接。 bottalkInstance.transport.loseConnection() 关闭由bottalkInstance.transport 表示的连接,按照惯例,bottalkInstance 正在与之交互的传输(即接收字节和发送字节)。无论 bottalk 实例变量的名称是 bottalkInstance 还是 self,都是如此。
    • 你说得非常有道理!一个扭曲的课程和一个蟒蛇课程合二为一。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-12
    • 2011-05-17
    • 2012-09-23
    • 1970-01-01
    • 1970-01-01
    • 2013-03-10
    相关资源
    最近更新 更多