4

Twistedサーバーに接続してインデックスを照会するこの単純なTwistedクライアントがあります。fnが表示された場合。connectionMade()class SpellClientqueryはハードコーディングされています。テスト目的でそれを行いました。このクエリを外部からこのクラスに渡すにはどうすればよいでしょうか。

コード -

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

1 に答える 1

5

SpellClientのようなプロトコルは、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')
...

...または、SpellFactoryの_ init _メソッドを作成して、そこに渡すこともできます。

于 2010-12-25T14:29:48.510 に答える