Skip to content

Instantly share code, notes, and snippets.

@iachievedit
Created August 16, 2014 18:15
Show Gist options
  • Save iachievedit/6870ef58c232577cdea0 to your computer and use it in GitHub Desktop.
Save iachievedit/6870ef58c232577cdea0 to your computer and use it in GitHub Desktop.
Switching protocols on Twisted
from twisted.web.server import Site
from twisted.web.http import HTTPChannel
from twisted.web.resource import Resource
from twisted.internet import reactor
class MyServer(Resource):
isLeaf = True
def render_GET(self, request):
if request.uri == "/switch":
request.channel.switchProtocol(None)
return "SWITCHED\r\n"
else:
return "PLAINTEXT\r\n"
class MyHTTPChannel(HTTPChannel):
switched = False
def switchProtocol(self, protocol):
print "switching protocols"
self.switched = True
def dataReceived(self, data):
if self.switched:
print "ive switched and must use my other protocol"
else:
HTTPChannel.dataReceived(self,data)
class MySite(Site):
protocol = MyHTTPChannel
server = MyServer()
reactor.listenTCP(7335, MySite(server))
reactor.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment