[Twisted-Python] Creating a hybrid server in Twisted

--text follows this line-- Hi, I'm trying to write a hybrid server that serves either HTTP or my own custom protocol depending on how it's addressed (distantly inspired by the IRC bouncer ZNC). If it receives a standard GET, POST, HEAD, etc. it sends HTTP traffic, or if it receives the bareword `CORDELIA', it switches to Cordelia mode. HTTP works fine with Twisted.Web. I can serve pages over HTTP (which is my desired outcome). However, I'm not sure how to write the Cordelia handling code. I've tried my own custom `render_CORDELIA' function, but it acts too much like HTTP (ie. it returns a result and terminates the connection), which is not what I want, as the protocol I've designed involves establishing a two-way conversation, not a single request and response pair. 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? Jashank -- Jashank Jeremy PGP: 0x25A5C309

Jashank Jeremy wrote: [...]
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?
You could override lineReceived along the lines of: def connectionMade(self): self.seenFirstLine = False HTTPChannel.connectionMade(self) def lineReceived(self, line): if not self.seenFirstLine and line == 'CORDELIA': # do your protocol switch; e.g. setRawMode and a flag to # pass all bytes directly to some other protocol. If you # want to be really hackish here you can reassign # self.__class__… else: self.seenFirstLine = True HTTPChannel.lineReceived(self, line) Alternatively, you could write a protocol decorator to do much the same thing (i.e. a Protocol that wraps around the HTTPChannel instance). There's some infrastructure in twisted.protocols.policies that may help you write that. (This sort of thing may make an interesting example to add to the examples in our docs. I can imagine it'd be possible to add a ProtocolSwitchingDecoratorBase or similar to twisted.protocols.policies to make it easier. It's not a common requirement, but it is something that people want to do from time to time. I know I've done it…) -Andrew.
participants (2)
-
Andrew Bennetts
-
Jashank Jeremy