如何从扭曲协议方法中修改变量,例如ConnectionMade

2024-09-30 08:27:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我对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    

Tags: pyself客户端dataserverinitportdef
2条回答

感谢您的及时回答,以及宝贵的建议,正如我在帖子中所说的,我对python还不熟悉,但已经准备好改进自己了

我已经分析了你们的变化,我开始理解原理,但有一件事我不明白:打电话给工厂\u init(self),而且这一行生成了一个错误,我将它们更改为ControllerFactory。init(self),最后我将其删除。我添加了一些遗漏的初始化,它可以工作,非常感谢:)

下面是我希望它按我的方式工作的最终代码

controller.py

class Controller(object):
    def __init__(self, port):
    # Don't set self.nodes as a class attribute or it is shared across all instances
    self.port = port
    self.nodes = [] 

    # Don't just use a local for SimpleServer, keep a reference on an attribute.  Also, pass the controller instance in.
    self.ss = SimpleServer(port, self)

server.py

class MyServerProtocol(Protocol):
    def connectionMade(self): 
        # Get the reference to the Controller instance.
        ctrl = self.factory.server.controller
        # Use it.
        ctrl.nodes.append(self.transport.getPeer())    

class ControllerFactory(Factory):
    # Set this class attribute so the inherited buildProtocol does the work for us, including setting the factory attribute.
    protocol = MyServerProtocol
    def __init__(self, server):
        # Save a reference to the given server as an attribute on the instance.
        self.server = server
        #ControllerFactory.__init__(self)

class SimpleServer():
    def __init__(self, port, controller):
        self.port = port
        self.controller = controller
        # Pass a reference to the SimpleServer instance to the ControllerFactory
        reactor.listenTCP(self.port, ControllerFactory(self))
        print 'server listening on %d' %port
        reactor.run() 

主程序

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 : [ 127.0.0.1 ] on [ 9123 ]\n" 
    reactor.connectTCP('127.0.0.1',9123, myClientFactory())
    reactor.run()
    现在我来考虑一下你的最后一句话。<李>

您只需要引用正确的对象

正如您需要对reactor的引用,因此导入了twisted.internet.reactor,以便可以调用run方法

controller.py

class Controller(object):
    def __init__(self, port):
        # Don't set self.nodes as a class attribute or it is shared across all instances
        self.nodes = [] 
        # Don't just use a local for SimpleServer, keep a reference on an attribute.  Also, pass the controller instance in.
        self.ss = SimpleServer(port, self)

server.py

class MyServerProtocol(Protocol):
    def connectionMade(self): 
        # Get the reference to the Controller instance.
        ctrl = self.factory.server.controller
        # Use it.
        ctrl.nodeList.append(self.transport.getPeer())    

class ControllerFactory(Factory):
    # Set this class attribute so the inherited buildProtocol does the work for us, including setting the factory attribute.
    protocol = MyServerProtocol
    def __init__(self, server):
        # Save a reference to the given server as an attribute on the instance.
        self.server = server
        Factory.__init__(self)

class SimpleServer():
    def __init__(self, port, controller):
        self.controller = controller
        # Pass a reference to the SimpleServer instance to the ControllerFactory
        reactor.listenTCP(port, ControllerFactory(self))
        print 'server listening on %d' %port
        reactor.run()

主程序

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    

我已经做了我能看到的最小的一组更改来演示解决方案。我还没有测试生成的代码。希望您能看到,我所做的是引用代码的一部分所拥有的对象,并将它们传递给代码中需要它们的其他部分。这通常采用将参数传递给函数(初始值设定项、方法等)和设置对象属性(通常是自身引用的对象)的形式

我没有试图提高代码的可维护性或纠正任何令人担忧的模式。这段代码仍然不是理想软件的模型,但它至少应该允许您将一个值附加到希望附加到的列表中

我还想提出一些其他建议:

  • 使用更具描述性的名称
  • 少用间接手段
  • 除了在self上设置属性外,不要使__init__产生副作用
  • 不要违反德墨忒尔的法律,所以要努力
  • 不要做任何你正在做的事情(可能是一个*导入?)

相关问题 更多 >

    热门问题