Domanda

ho questo semplice ritorto client che si collega a un server ritorto & interroga un indice. Se si vede fn. connectionMade() nel class SpellClient, il query è hard-coded. Ha fatto che per scopi di test. Come si potrebbe passare questa query dall'esterno verso questa classe?

Il codice -

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()
È stato utile?

Soluzione

Protocolli, come SpellClient, avere accesso ai propri fabbrica come self.factory.
... quindi ci sarebbe un certo numero di modi per farlo, ma un modo sarebbe quello di creare un altro metodo su SpellFactory, come ad esempio setQuery, e l'accesso quindi che dal client ...

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


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

... quindi in principale:

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

... o si può solo creare un _ init _ metodo per SpellFactory, e passarlo in là.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top