annot-server/annotserver.py
author ymh <ymh.work@gmail.com>
Wed, 08 Oct 2014 15:14:58 +0200
changeset 0 e1d4d7a8255a
child 2 fc1ab0074e29
permissions -rw-r--r--
First shareable version


from autobahn.twisted.resource import WebSocketResource, \
                                      WSGIRootResource, \
                                      HTTPChannelHixie76Aware


from twisted.application import service, internet, strports
from twisted.internet import reactor
from twisted.python.threadpool import ThreadPool
from twisted.web import server
from twisted.web.wsgi import WSGIResource
from twisted.web.static import Data

from oscserver import OSCServerProtocol
from websockets import BroadcastServerFactory, AnotationServerFactory
from webapp import app


WEB_PORT = 8080
WS_PORT = 8090
OSC_PORT = 9090

def make_service(config, conn, debug=False):

    s = service.MultiService()
    # Create and start a thread pool,
    wsgiThreadPool = ThreadPool()
    wsgiThreadPool.start()

    # ensuring that it will be stopped when the reactor shuts down
    reactor.addSystemEventTrigger('after', 'shutdown', wsgiThreadPool.stop)


    wsFactory = BroadcastServerFactory("ws://localhost:%d/broadcast" % config.get('ws_port',WS_PORT),
                                       debug = debug,
                                       debugCodePaths = debug)
    wsFactory.setProtocolOptions(allowHixie76 = True)
    wsResource = WebSocketResource(wsFactory)


    wsAnnotFactory = AnotationServerFactory("ws://localhost:%d/annot" % config.get('ws_port',WS_PORT),
                                       debug = debug,
                                       debugCodePaths = debug,
                                       ws_factory = wsFactory,
                                       conn = conn)
    wsAnnotFactory.setProtocolOptions(allowHixie76 = True)
    wsAnnotResource = WebSocketResource(wsAnnotFactory)


    rootWs = Data("", "text/plain")

    rootWs.putChild("broadcast", wsResource)
    rootWs.putChild("annot", wsAnnotResource)


    # Create the WSGI resource
    wsgiAppAsResource = WSGIResource(reactor, wsgiThreadPool, app)

    # Hooks for twistd

    webserver = strports.service('tcp:%d' % config.get('web_port',WEB_PORT), server.Site(wsgiAppAsResource))
    webserver.setServiceParent(s)

    wsserver = strports.service('tcp:%d' % config.get('ws_port',WS_PORT), server.Site(rootWs))
    wsserver.setServiceParent(s)

    oscservice = internet.UDPServer(config.get('osc_port',OSC_PORT), OSCServerProtocol(wsFactory, conn))
    oscservice.setServiceParent(s)

    return s