使用twisted,我该如何保留客户端对象

时间:2015-03-13 16:06:57

标签: python object twisted

这是我简单的扭曲服务器代码:

from twisted.internet.protocol import Protocol,Factory
from twisted.internet import reactor

class MultiEcho(Protocol):
    def __init__(self, factory):
        self.recvBuf = ""
        self.factory = factory

    def connectionMade(self):
        self.factory.echoers.append(self)
        print self.factory.echoers

    def dataReceived(self, data):
        self.recvBuf += data
        self.transport.write(data)

    def connectionLost(self, reason):
        self.factory.echoers.remove(self)

class MultiEchoFactory(Factory):
    def __init__(self):
        self.echoers=[]

    def buildProtocol(self, addr):
        return MultiEcho(self)

if __name__ == '__main__':
    reactor.listenTCP(4321, MultiEchoFactory())
    reactor.run()

使用' telnet 127.0.0.1 4321' ,将打印一份清单:

[<__main__.MultiEcho instance at 0x0000000002EA6B08>]

添加另一个&#39; telnet 127.0.0.1 4321&#39;,列表是:

[<__main__.MultiEcho instance at 0x0000000002EA6B08>, <__main__.MultiEcho instance at 0x0000000002EA6EC8>]

我知道客户端是协议对象的实例,列表是MultiEchoFactory.echoers,所以我想保留列表, 使用list[n].transport.write(somedata)将其导入另一个.py文件。

我尝试from myserver import MultiEchoFactory,但MultiEchoFactory.echoers为空。 我也重写了代码

class MultiEchoFactory(Factory):
    def __init__(self):
        self.echoers=[]

class MultiEchoFactory(Factory):
    echoers=[]

但我仍然无法在另一个.py文件中使用协议列表。 那么,我该怎么办?

1 个答案:

答案 0 :(得分:1)

您需要将其保存在buildProtocol()中,即:

class MultiEchoFactory(Factory):
    echoers=[]

    def buildProtocol(self, addr):
        echoer = MultiEcho(self)
        MultiEchoFactory.echoers.append(echoer)
        return echoer