Reputation: 21
Here is my simple twisted server code:
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()
Use 'telnet 127.0.0.1 4321' ,will print a list:
[<__main__.MultiEcho instance at 0x0000000002EA6B08>]
add another 'telnet 127.0.0.1 4321',the list is:
[<__main__.MultiEcho instance at 0x0000000002EA6B08>, <__main__.MultiEcho instance at 0x0000000002EA6EC8>]
I know a client is a protocol object's instance ,and the list is MultiEchoFactory.echoers
,so I want to keep the list,
import them in another .py file use list[n].transport.write(somedata)
.
I try from myserver import MultiEchoFactory
,but the MultiEchoFactory.echoers is empty.
I also rewrite the code
class MultiEchoFactory(Factory):
def __init__(self):
self.echoers=[]
to
class MultiEchoFactory(Factory):
echoers=[]
But I still can't use the protocol list in another .py file. So,what should I do?
Upvotes: 2
Views: 121
Reputation: 11504
You need to save it in buildProtocol()
, i.e.:
class MultiEchoFactory(Factory):
echoers=[]
def buildProtocol(self, addr):
echoer = MultiEcho(self)
MultiEchoFactory.echoers.append(echoer)
return echoer
Upvotes: 1