【问题标题】:Python Twisted ClientPython 扭曲客户端
【发布时间】:2011-05-30 14:52:07
【问题描述】:

我有一个简单的 Twisted 客户端,它连接到 Twisted 服务器并查询索引。 如果你看到 fn. connectionMade()class SpellClient 中,query 是硬编码的。这样做是出于测试目的。如何将这个查询从外部传递给这个类?

代码 -

from twisted.internet import reactor
from twisted.internet import protocol

# a client protocol
class SpellClient(protocol.Protocol):
    """Once connected, send a message, then print the result."""

    def connectionMade(self):
        query = 'abased'
        self.transport.write(query)

    def dataReceived(self, data):
        "As soon as any data is received, write it back."
        print "Server said:", data
        self.transport.loseConnection()

    def connectionLost(self, reason):
        print "connection lost"

class SpellFactory(protocol.ClientFactory):
    protocol = SpellClient

    def clientConnectionFailed(self, connector, reason):
        print "Connection failed - goodbye!"
        reactor.stop()

    def clientConnectionLost(self, connector, reason):
        print "Connection lost - goodbye!"
        reactor.stop()

# this connects the protocol to a server runing on port 8000
def main():
    f = SpellFactory()
    reactor.connectTCP("localhost", 8090, f)
    reactor.run()

# this only runs if the module was *not* imported
if __name__ == '__main__':
    main()

【问题讨论】:

    标签: python twisted twisted.internet twisted.client


    【解决方案1】:

    协议,如 SpellClient,可以作为 self.factory 访问其工厂。
    ...所以有很多方法可以做到这一点,但一种方法是在 SpellFactory 上创建另一种方法,例如 setQuery,然后从客户端访问它...

    #...in SpellFactory:  
    def setQuery(self, query):
        self.query = query
    
    
    #...and in SpellClient:
    def connectionMade(self):
        self.transport.write(self.factory.query)
    

    ...所以主要:

    f = SpellFactory()
    f.setQuery('some query')
    ...
    

    ...或者您可以为 SpellFactory 创建一个 _init_ 方法,然后将其传递进去。

    【讨论】:

      猜你喜欢
      • 2012-09-13
      • 2011-01-09
      • 1970-01-01
      • 1970-01-01
      • 2013-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-09
      相关资源
      最近更新 更多