简体   繁体   English

Python Twisted Client

[英]Python Twisted Client

I have this simple Twisted Client which connects to a Twisted server & queries an index. 我有这个简单的Twisted Client连接到Twisted服务器并查询索引。 If you see fn. 如果你看到fn。 connectionMade() in class SpellClient , the query is hard-coded. class SpellClient connectionMade()query是硬编码的。 Did that for testing purposes. 这是为了测试目的。 How would one pass this query from outside to this class? 如何将此查询从外部传递给此类?

The code - 代码 -

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()

Protocols, like SpellClient, have access to their factory as self.factory. 像SpellClient这样的协议可以作为self.efactory访问他们的工厂。
...so there would be a number of ways to do this, but one way would be to create another method on SpellFactory, such as setQuery, and then access that from the client... ...所以有很多方法可以做到这一点,但有一种方法是在SpellFactory上创建另一个方法,比如setQuery,然后从客户端访问它...

#...in SpellFactory:  
def setQuery(self, query):
    self.query = query


#...and in SpellClient:
def connectionMade(self):
    self.transport.write(self.factory.query)

...so in main: ...所以在主要:

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

...or you could just create an _ init _ method for SpellFactory, and pass it in there. ...或者您可以为SpellFactory创建一个_ init _方法,并将其传递给那里。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM