ping循环中的Python-Twisted client-check协议.transport连接
我正在用Twisted创建TCP客户端套接字。我需要在ConnectionMode方法中检查循环间隔中的连接状态ping循环中的Python-Twisted client-check协议.transport连接,python,sockets,python-3.x,twisted,twisted.internet,Python,Sockets,Python 3.x,Twisted,Twisted.internet,我正在用Twisted创建TCP客户端套接字。我需要在ConnectionMode方法中检查循环间隔中的连接状态 from twisted.internet import reactor, protocol class ClientProtocol(protocol.Protocol): def connectionMade(self): while not thread_obj.stopped.wait(10): print ('ping')
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
方法以捕获断开。
编辑关于重新连接:
重新连接主要是一个逻辑决定。您可能需要在“connectionLost”和“reconnect”之间添加逻辑
反正,
您可以使用它来获得更好的代码。
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)
while循环在
connectionMade
中做什么?它是否阻止connectionMade
返回?@keturn感谢您的关注,connectionMade
中的循环用于检查或ping连接,并在连接丢失时通知。此循环不会阻止返回。但是打印问题,从服务器断开连接后从未更改。我需要知道如何检查连接状态,如果是断开连接,如何重新连接?感谢您的回答。您的意思是我不需要在间隔循环中检查连接??您的意思是如果连接断开,将调用connectionLost
方法自动地?如果是真的,我怎么能重新连接呢?最好给我示例代码或参考:)是的。没错。你会忘记使用扭曲的循环:D