
Jashank Jeremy <jashank.jeremy@optusnet.com.au> writes:
So I'm pretty much stuck in a rut. I don't want to totally reinvent the wheel just to be able to protocol-switch; I'd prefer to make use of existing code from Twisted. How do I hijack Twisted.Web to add protocol switching?
The default HTTPFactory (of which Site is a subclass) is going to create an HTTPChannel protocol for a new connection. HTTPChannel is based on LineReceiver, so lineReceived() is your hook for incoming data. To insert your own protocol code, you want to set the "protocol" attribute of your Site (or HTTPFactory if using that directly) instance to your own "hybrid" protocol class. That protocol class needs to be able to use HTTPChannel for web connections, so you can choose between subclassing or composition. Subclassing is probably simpler, at least at first, since you won't have to worry about mirroring instance parameters or attributes getting set on your protocol instance by the factory, though composition may perhaps keep your protocols separate more cleanly. In your protocol's lineReceived() method, check for your flag value, and adjust state appropriately. Depending on the state you are in, either pass along control to HTTPChannel.lineReceived, or just process the data yourself. Note that if your protocol is binary so you are implementing rawDataReceived, you'll also want to check state and pass along to HTTPCHannel if not in your local mode since that can be used on web connections too. If you're subclassing be aware that any standard protocol method you implement might also get called on behalf of the HTTPChannel code and not just your own protocol so always pass along such calls if your local protocol mode isn't enabled. HTTPChannel also includes policies.TimeoutMixin, so if you end up switching to your own protocol, calling setTimeout(None) should prevent it from deciding to close down your transport beneath you. Unless you're subclassing and you'd like the same timeout to be in effect for your own protocol, of course. -- David