Search code examples
pythonpython-2.7twistedtwisted.client

Twisted continues to block after connection fails


I'm working on a relatively simple project that uses the Python Twisted module. It appears to be working well, except when a connection fails on the client's end (I purposely didn't start the host server to get this issue) it continues to block and the program never finishes.

Here's a simplified example of what I'm trying to do that replicates this issue:

#!/etc/python2.7
from twisted.internet import reactor, protocol



class Client_Protocol(protocol.Protocol):

    def connectionMade(self):
        print "A connection was made!"


class Client_Factory(protocol.ClientFactory):
    def buildProtocol(self, addr):
        return Client_Protocol()

    def clientConnectionFailed(self, connector, reason):
        print "Connection Failed!"


factory = Client_Factory()

reactor.connectTCP("localhost", 8000, factory)
reactor.run()

The result is the program prints out "Connection Failed!" as you'd expect (As long as the host wasn't running). But the code never finishes when the connection fails. It continues to block. How do I stop it?

I've looked online at alternative asynchronous methods (like reactor.callInThread and reactor.callFromThread). I've tried the "deferToThread". But no matter what, the client never seems to stop blocking after a connection fails.


Solution

  • I've figured out the answer after some more reading and experimenting around. It was surprisingly simple. The trick is to add a "reactor.stop()" call in the "clientConnectionFailed" function.

    Like So:

    def clientConnectionFailed(self, connector, reason):
        print "Connection Failed!"
        reactor.stop()