I create my connection to a server like this:
connection = TCP4ClientEndPoint(reactor, server_host, server_port)
factory = Factory()
factory.protocol = Protocol
protocol = yield connection.connect(factory)
protocol.doSomething() # returns a deferred
Now, in some other method, where i have a handle on this protocol object I want to test if protocol is still connected, something like:
if protocol.isConnected():
doSomethingElse()
Is there any way to do this. I looked at the twisted documentation and couldnt find a relevant method. Setting a flag in the connectionLost() callback is an option, but I was wondering if I could avoid doing that.
Twisted tries to be as light as possible when it comes to stored state. Just as bare factories keep absolutely no track of their children, Protocols
know very little about themselves. They are mostly callback bags.
Setting a flag in the connectionLost()
method is the way to do it. For future reference:
from twisted.internet.protocol import Protocol
class StatefulProtocol(Protocol):
def __init__(self, factory):
self.connected = False
def connectionMade(self):
self.connected = True
def connectionLost(self, reason):
self.connected = False
Edit: note that there's a reason this feels uncomfortable. If you have a method that needs to ask this question, you are probably working outside the callback chain. If you were running code exclusively within the life-cycle methods exposed by the Protocol
, you may not need this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With