gpt4 book ai didi

python - 使用扭曲,我怎样才能保留客户端对象

转载 作者:太空宇宙 更新时间:2023-11-04 05:53:22 25 4
gpt4 key购买 nike

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

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

我知道客户端是协议(protocol)对象的实例,列表是MultiEchoFactory.echoers ,所以我想保留 list ,将它们导入另一个 .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 文件中使用协议(protocol)列表。那么,我该怎么办?

最佳答案

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

class MultiEchoFactory(Factory):
echoers=[]

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

关于python - 使用扭曲,我怎样才能保留客户端对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29036924/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com