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

℡╲_俬逩灬. 提交于 2019-11-30 18:08:10

问题


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?


回答1:


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/




回答2:


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.



来源:https://stackoverflow.com/questions/9502090/twisted-how-can-i-identify-protocol-on-initial-connection-then-delegate-to-app

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!