[Twisted-Python] Creating a hybrid server in Twisted
Andrew Bennetts
andrew at bemusement.org
Mon Apr 4 05:43:20 EDT 2011
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.
More information about the Twisted-Python
mailing list