Question

I have a twisted tcp client that I would like to periodically cause to connect, receive a stream of date for n seconds, then disconnect. After disconnecting n seconds would elapse before the process started over again.

Below is a very abbreviated extract of the code I've tried so far. When I run the code the reactor.stop() is issued, and after the sleep elapses I get a twisted.internet error 'ReactorAlreadyRunning' when the reactor.run() is invoked in startClientConnection()

I'm a raw novice at using twisted and I'm not sure what I've done wrong. Any help will be much appreciated.

class TCPClientFactory(ReconnectingClientFactory)
   def startedConnecting(self, connector):
       pass

   def buildProtocol(self, addr):
       self.resetDelay()
       return MsgProcessor()

   def clientConnectionLost(self, connector, reason):
       ReconnectingClientFactory.clientConnectionLost(self, connector, reason)

   def clientConnectionFailed(self, connector, reason):
       ReconnectingClientFactory.clientConnectionFailed(self, connector, reason)        


class mainClass(object):
    def __init__(self):
        ...

    def startClientConnection(self):
        reactor.connectTCP(host, port, TCPClientFactory())
        reactor.callLater(60, self.periodic_connect_manager)
        reactor.run()

    def periodic_connect_manager(self):
        reactor.stop()
        time.sleep(60)
        self.startClientConnection()
Was it helpful?

Solution

reactor.run() should be run only once.

from twisted.internet import task, reactor

def connect():
    do_connect()
    reactor.callLater(60, disconnect) # disconnect in a minute

task.LoopingCall(connect).start(120) # call connect() every 2 minutes
reactor.run()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top