質問

Twisted Serverに接続し、インデックスをクエリするこのシンプルなねじれたクライアントがあります。 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()
役に立ちましたか?

解決

Plertcolsは、Spellclientのように、Factoryにself.factoryとしてアクセスできます。
...したがって、これを行うにはいくつかの方法がありますが、1つの方法は、SetQueryなどのSpellFactoryで別の方法を作成し、クライアントからアクセスすることです...

#...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')
...

...またはあなたは_を作成することができます初期化_スペルファクタリーの方法、そしてそこに渡します。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top