Python Twisted客户端

4 投票
1 回答
2201 浏览
提问于 2025-04-16 09:01

我有一个简单的Twisted客户端,它可以连接到一个Twisted服务器并查询一个索引。如果你查看class SpellClient中的connectionMade()函数,你会发现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()

1 个回答

5

协议,比如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_方法,然后在这里传入相关内容。

撰写回答