2015-09-02 69 views
1

我使用Twisted创建TCP客户端套接字。我需要在connectionMade方法的循环间隔中检查连接状态。Python - 扭曲客户端 - 在ping回路中检查protocol.transport连接

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) 

但是,任何变量值断开我的网络后,并没有改变:(

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

+1

''connectionMade'里面做的while循环是什么?它是否阻止'connectionMade'返回? – keturn

+0

@keturn感谢您的关注,'connectionMade'内的循环用于检查或ping连接,并在连接丢失时通知。此循环不会阻止返回。但是我打印的值在从服务器断开连接后从未更改过。我需要知道如何检查连接状态,如果断开连接,我该如何重新连接? –

回答

1

覆盖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) 
+0

感谢您的回复。你的意思是我不需要检查间隔循环中的连接?你的意思是如果连接丢失,'connectionLost'方法将自动调用?如果这是真的,我该如何重新连接?如果你给我示例代码或参考:) –

+0

是的。你会忘记用扭曲的方式使用循环:D – cengizkrbck