Skip to content

Instantly share code, notes, and snippets.

@hamsolodev
Created May 6, 2015 06:56
Show Gist options
  • Save hamsolodev/5d377f47df8f42f4c80d to your computer and use it in GitHub Desktop.
Save hamsolodev/5d377f47df8f42f4c80d to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
from autobahn.twisted.resource import WebSocketResource
from autobahn.twisted.websocket import WampWebSocketServerFactory
from crossbar.router.router import RouterFactory
from crossbar.router.session import RouterSessionFactory
from twisted.application import internet, service
from twisted.application.service import IServiceMaker
from twisted.plugin import IPlugin
from twisted.python import usage
from twisted.web.resource import Resource
from twisted.web.server import NOT_DONE_YET, Site
from zope.interface import implements
class ApiRoot(Resource):
def render_GET(self, request):
request.setHeader('Content-type', 'application/json')
request.write('{"msg": "hello"}')
if not request.finished:
request.finish()
return NOT_DONE_YET
class WebSocketParentResource(Resource):
allowedMethods = ('POST', 'GET', 'OPTIONS', 'HEAD',)
class Options(usage.Options):
optParameters = [
['websocketport', 'w', 50000, 'port for WebSocket server'], # noqa
['wsurl', 'u', 'ws://localhost:50000', 'WebSocket URL'], # noqa
['httpport', 'p', 50001, 'port for HTTP server'], # noqa
]
class MyappServiceMaker(object):
implements(IServiceMaker, IPlugin)
tapname = 'myapp'
description = 'description of my app'
options = Options
def makeService(self, options):
"""Make a service combining REST, WAMP &c. into a single MultiService
"""
top_service = service.MultiService()
# construct and add a simple web service
root = ApiRoot()
WebFactory = Site(root)
rest_service = internet.TCPServer(int(options['httpport']),
WebFactory)
rest_service.setServiceParent(top_service)
# Create a WAMP router factory
router_factory = RouterFactory()
# Create a WAMP router session factory
session_factory = RouterSessionFactory(router_factory)
root = WebSocketParentResource()
# Create a WAMP transport server factory
ws_transport_factory = WampWebSocketServerFactory(
session_factory,
str(options['wsurl']))
ws_transport_factory.setProtocolOptions(failByDrop=False)
ws_resource = WebSocketResource(ws_transport_factory)
# And our websocket server under /ws
root.putChild('ws', ws_resource)
WampFactory = Site(root)
wamp_service = internet.TCPServer(int(options['websocketport']),
WampFactory)
wamp_service.setServiceParent(top_service)
return top_service
serviceMaker = MyappServiceMaker()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment