扭曲-我需要定期连接/断开客户端连接 [英] Twisted - I need to periodically connect/disconnect a client connection

查看:16
本文介绍了扭曲-我需要定期连接/断开客户端连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个扭曲的TCP客户端,我希望定期进行连接,在n秒内接收数据流,然后断开连接。 断开连接后,将经过%n秒后该进程才会重新开始。

下面是我到目前为止尝试过的代码的一个非常简短的摘录。 当我运行代码时,会发出reactor.top(),在休眠时间过后,我会收到两个.Internet错误:在startClientConnection()中调用reactor.run()时出现‘Reactor.run’错误

我是使用Twisted的新手,我不确定我做错了什么。任何帮助都将不胜感激。

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

推荐答案

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

这篇关于扭曲-我需要定期连接/断开客户端连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆