jeremytrimble
jeremytrimble

Reputation: 1834

Twisted: How can I identify protocol on initial connection, then delegate to appropriate Protocol implementation?

I'm writing a Python program that will use Twisted to connect to a TCP server. The server on the other end of the socket might be running one of two possible protocols (protoA or protoB), but I won't know which one it is until I've initiated the connection and "asked" the server which protocol is being used. I'm able to identify which version of the protocol (protoA or protoB) is being used once I've connected, but I don't know it ahead of time.

Obviously, one solution is to have a lot of special-case code in my twisted Protocol-derived class -- i.e. if protoA do this elif protoB do something else. However, I'd like to be able to keep the code for the two separate protocols in two separate Protocol implementations (though they might share some functionality through a base class). Since both versions of the protocol involve maintaining state, it could quickly get confusing to have to mash both versions into the same class.

How can I do this? Is there a way to perhaps do the initial "protocol identification" step in the Factory implementation, then instantiate the correct Protocol derivative?

Upvotes: 3

Views: 894

Answers (2)

Jean-Paul Calderone
Jean-Paul Calderone

Reputation: 48325

Instead of mixing the decision logic all throughout your protocol implementation, put it in one place.

class DecisionProtocol(Protocol):
    def connectionMade(self):
        self.state = "undecided"

    def makeProgressTowardsDecision(self, bytes):
        # Do some stuff, eventually return ProtoA() or ProtoB()

    def dataReceived(self, bytes):
        if self.state == "undecided":
            proto, extra = self.makeProgressTowardsDecision(bytes)
            if proto is not None:
                self.state = "decided"
                self.decidedOnProtocol = proto
                self.decidedOnProtocol.makeConnection(self.transport)
                if extra:
                    self.decidedOnProtocol.dataReceived(extra)

        else:
            self.decidedOnProtocol.dataReceived(bytes)

    def connectionLost(self, reason):
        if self.state == "decided":
            self.decidedOnProtocol.connectionLost(reason)

Eventually you may be able to implement this with a bit less boilerplate: http://tm.tl/3204/

Upvotes: 4

technillogue
technillogue

Reputation: 1571

This is easily done with some magic.

class MagicProtocol(Protocol):
    ...
    def dataReceived(self, data):
        protocol = self.decideProtocol(data)
        for attr in dir(protocol):
            setattr(self, attr, getattr(protocol, attr))

This is ugly, but it would effectivly switch out the Magic protocol for the choosen protocol.

Upvotes: 1

Related Questions