Search code examples
pythontwisted

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?


Solution

  • 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/