Python - Twisted 客户端 - 检查 ping 循环中的 protocol.transport 连接

标签 python sockets python-3.x twisted twisted.internet

我正在使用 Twisted 创建 TCP 客户端套接字。我需要在connectionMade方法中的循环间隔中检查连接状态。

from twisted.internet import reactor, protocol

class ClientProtocol(protocol.Protocol):
    def connectionMade(self):
       while not thread_obj.stopped.wait(10):
            print ('ping')
            self.transport.write(b'test') # Byte value

为了检查连接丢失,我手动断开网络,然后我检查了一些变量,如下所示:

print (self.connected)
print (self.transport.connector.state)
print (self.transport.connected)
print (self.transport.reactor.running)
print (self.transport.socket._closed)
print (self.factory.protocol.connected)
print (self._writeDissconnected)

但是断开网络后任何变量值都没有改变:(

我的问题是:连接丢失时会设置哪些变量?我的意思是如何检查连接状态,如果断开连接,如何重新连接?

最佳答案

重写connectionLost方法来捕获断开连接。 to official docs

关于重新连接的编辑: 重新连接主要是一个合乎逻辑的决定。您可能需要在“connectionLost”和“reconnect”之间添加逻辑。

无论如何, 您可以使用ReconnectingClientFactory为了更好的代码。 ps:在重新连接时使用工厂模式是保持代码整洁和智能的最佳方法。

class MyEchoClient(Protocol):
    def dataReceived(self, data):
        someFuncProcessingData(data)
        self.transport.write(b'test')

class MyEchoClientFactory(ReconnectingClientFactory):
    def buildProtocol(self, addr):
        print 'Connected.'
        return MyEchoClient()

    def clientConnectionLost(self, connector, reason):
        print 'Lost connection.  Reason:', reason
        ReconnectingClientFactory.clientConnectionLost(self, connector, reason)

    def clientConnectionFailed(self, connector, reason):
        print 'Connection failed. Reason:', reason
        ReconnectingClientFactory.clientConnectionFailed(self, connector,
                                                     reason)

关于Python - Twisted 客户端 - 检查 ping 循环中的 protocol.transport 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32351684/

相关文章:

C - 从套接字写入和读取

java - 将字符串从控制台输入传递到 TCP 套接字

Python:如何优化函数参数?

apache-flex - Adobe Flex : Why do I get intermittent SecurityErrorEvents on some browsers?

Python 多处理竞争条件

python - 将队列与 tkinter(和线程)一起使用

Python 正则表达式与年月组合不匹配

python - 联合异步迭代器会发生什么?

python - 在 Django 中迁移时依赖项引用不存在的父节点错误

python - 我想通过(Python)为解压缩(.tar.gz)文件创建一个脚本