扭曲 - 我需要周期性地连接/断开客户机连接(Twisted - I need to periodi

2019-10-19 02:58发布

我有一个扭曲的TCP客户端,我想周期性地使连接,接收日期的流n秒,然后断开。 启动进程再次断开前n秒后就会过去。

下面是到目前为止我试过的代码非常简短的提取物。 当我运行的代码reactor.stop()被发出,并且睡眠过去之后,我收到了twisted.internet错误“ReactorAlreadyRunning”当reactor.run()在startClientConnection被调用()

我在用扭曲的原始新手,我不知道我做错了。 任何帮助都感激不尽。

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

Answer 1:

reactor.run()应只运行一次。

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


文章来源: Twisted - I need to periodically connect/disconnect a client connection