簡體   English   中英

Python Twisted Client

[英]Python Twisted Client

我有這個簡單的Twisted Client連接到Twisted服務器並查詢索引。 如果你看到fn。 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()

像SpellClient這樣的協議可以作為self.efactory訪問他們的工廠。
...所以有很多方法可以做到這一點,但有一種方法是在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 _方法,並將其傳遞給那里。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM