Search code examples
pythontwistedtwisted.internettwisted.client

Python Twisted Client


I have this simple Twisted Client which connects to a Twisted server & queries an index. If you see fn. connectionMade() in class SpellClient, the query is hard-coded. 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()

Solution

  • Protocols, like SpellClient, have access to their factory as self.factory.
    ...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...

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