2015-03-13 30 views
2

这里是我的简单扭曲的服务器代码:使用双绞线,我怎能客户对象

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>] 

加另一个用 'telnet 127.0.0.1 4321',该名单是:

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

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

我试着from myserver import MultiEchoFactory,但MultiEchoFactory.echoers是空的。 我也代码

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

改写为

class MultiEchoFactory(Factory): 
    echoers=[] 

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

回答

1

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

class MultiEchoFactory(Factory): 
    echoers=[] 

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

对不起球员,我尝试,但它不是useful.from XX进口MultiEchoFactory,该echoers = [] – Blunt 2015-03-14 11:06:18

+0

@Blunt:我更新了我的答案,但请小心使用全局状态,如'echoers'列表。 – myaut 2015-03-14 19:21:47

+0

对不起,仍然无法工作......也许我不能用这样扭曲? – Blunt 2015-03-16 05:47:58