我对python和Twisted都是新手,如果标题不够清楚,我很抱歉,但我会尽力描述我的问题
我想在我的应用程序中分离逻辑和网络部分,所以我有两个类Controller和SimpleServer,我在Controller中有一个名为nodes的变量,我想通过添加每个连接的客户端Ip来更新它,这对于python专家来说可能是显而易见的,但我无法得到它。请看一下我的代码。我评论了我被卡住的地方
谢谢你的帮助
controller.py
class Controller(object):
nodes = []
def __init__(self, port):
ss= SimpleServer(port)
server.py
class MyServerProtocol(Protocol):
def connectionMade(self):
#ctrl.nodeList.append(self.transport.getPeer()) #this is what I want to do
class ControllerFactory(Factory):
def buildProtocol(self, addr):
return MyServerProtocol()
class SimpleServer():
def __init__(self, port):
reactor.listenTCP(port, ControllerFactory()) #@UndefinedVariable
print 'server listening on %d' %port
reactor.run() #@UndefinedVariable
主程序
if __name__ == '__main__':
port = 9123
ctrl = Controller(port)
客户端
class myClientProtocol(Protocol):
def dataReceived(self, data):
print ("data received", data)
class myClientFactory(ClientFactory):
def buildProtocol(self, addr):
print 'Connected.'
return myClientProtocol()
if __name__ == '__main__':
print "CLIENT : connecting to : [ %s ] on [ %s ]\n" %(IP,PORT)
reactor.connectTCP('127.0.0.1',9123, myClientFactory()) #@UndefinedVariable
reactor.run() #@UndefinedVariable
感谢您的及时回答,以及宝贵的建议,正如我在帖子中所说的,我对python还不熟悉,但已经准备好改进自己了
我已经分析了你们的变化,我开始理解原理,但有一件事我不明白:打电话给工厂\u init(self),而且这一行生成了一个错误,我将它们更改为ControllerFactory。init(self),最后我将其删除。我添加了一些遗漏的初始化,它可以工作,非常感谢:)
下面是我希望它按我的方式工作的最终代码
controller.py
server.py
主程序
客户端
现在我来考虑一下你的最后一句话。<李>
您只需要引用正确的对象
正如您需要对reactor的引用,因此导入了
twisted.internet.reactor
,以便可以调用run方法controller.py
server.py
主程序
客户端
我已经做了我能看到的最小的一组更改来演示解决方案。我还没有测试生成的代码。希望您能看到,我所做的是引用代码的一部分所拥有的对象,并将它们传递给代码中需要它们的其他部分。这通常采用将参数传递给函数(初始值设定项、方法等)和设置对象属性(通常是自身引用的对象)的形式
我没有试图提高代码的可维护性或纠正任何令人担忧的模式。这段代码仍然不是理想软件的模型,但它至少应该允许您将一个值附加到希望附加到的列表中
我还想提出一些其他建议:
self
上设置属性外,不要使__init__
产生副作用*
导入?)李>相关问题 更多 >
编程相关推荐