Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if a twisted.internet.protocol instance has disconnected

Tags:

python

twisted

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.

like image 840
AnkurVj Avatar asked Apr 18 '13 16:04

AnkurVj


1 Answers

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.

like image 135
slezica Avatar answered Nov 15 '22 08:11

slezica