Пример #1
0
 def __init__(self, cacher):
     router = TornadioRouter(Client)
     self.server = None
     self.cacher = cacher
     self.reportUUID = uuid.uuid4().hex
     self.app = tornado.web.Application(
         router.apply_routes([
             (r"/", MainHandler,
              dict(template='index.jade',
                   reportUUID=self.reportUUID,
                   cacher=cacher)),
             (r"/offline\.html", MainHandler,
              dict(template='offline.jade',
                   reportUUID=self.reportUUID,
                   cacher=cacher)),
             (r"/brief\.html$", MainHandler,
              dict(template='brief.jade',
                   reportUUID=self.reportUUID,
                   cacher=cacher)),
             (r"/monitoring\.html$", MainHandler,
              dict(template='monitoring.jade',
                   reportUUID=self.reportUUID,
                   cacher=cacher)),
             (r"/data\.json$", JsonHandler,
              dict(reportUUID=self.reportUUID, cacher=cacher)),
         ]),
         template_path=os.path.join(os.path.dirname(__file__), "templates"),
         static_path=os.path.join(os.path.dirname(__file__), "static"),
         debug=True,
     )
Пример #2
0
def start_warrior_server(warrior, port_number=8001):
  SeesawConnection.warrior = warrior

  warrior.on_projects_loaded += SeesawConnection.handle_projects_loaded
  warrior.on_project_refresh += SeesawConnection.handle_project_refresh
  warrior.on_project_installing += SeesawConnection.handle_project_installing
  warrior.on_project_installed += SeesawConnection.handle_project_installed
  warrior.on_project_installation_failed += SeesawConnection.handle_project_installation_failed
  warrior.on_project_selected += SeesawConnection.handle_project_selected
  warrior.on_status += SeesawConnection.handle_warrior_status
  warrior.runner.on_pipeline_start_item += SeesawConnection.handle_start_item
  warrior.runner.on_pipeline_finish_item += SeesawConnection.handle_finish_item
  warrior.runner.on_status += SeesawConnection.handle_runner_status

  ioloop.PeriodicCallback(SeesawConnection.broadcast_bandwidth, 1000).start()

  router = TornadioRouter(SeesawConnection)
  application = web.Application(
    router.apply_routes([(r"/(.*\.(html|css|js|swf|png))$",
                          web.StaticFileHandler, {"path": PUBLIC_PATH}),
                         ("/", IndexHandler),
                         ("/api/(.+)$", ApiHandler, {"warrior": warrior})]),
#   flash_policy_port = 843,
#   flash_policy_file = os.path.join(PUBLIC_PATH, "flashpolicy.xml"),
    socket_io_port = port_number,
    debug = True
  )
  SocketServer(application, auto_start=False)
Пример #3
0
 def __init__(self, cacher):
     router = TornadioRouter(Client)
     self.server = None
     self.cacher = cacher
     self.reportUUID = uuid.uuid4().hex
     self.app = tornado.web.Application(
         router.apply_routes([
             (r"/", MainHandler, dict(
                 template='index.jade',
                 reportUUID=self.reportUUID,
                 cacher=cacher)),
             (r"/offline\.html", MainHandler, dict(
                 template='offline.jade',
                 reportUUID=self.reportUUID,
                 cacher=cacher)),
             (r"/brief\.html$", MainHandler, dict(
                 template='brief.jade',
                 reportUUID=self.reportUUID,
                 cacher=cacher)),
             (r"/monitoring\.html$", MainHandler, dict(
                 template='monitoring.jade',
                 reportUUID=self.reportUUID,
                 cacher=cacher)),
             (r"/data\.json$", JsonHandler,
                 dict(reportUUID=self.reportUUID, cacher=cacher)),
         ]),
         template_path=os.path.join(os.path.dirname(__file__), "templates"),
         static_path=os.path.join(os.path.dirname(__file__), "static"),
         debug=True,
     )
Пример #4
0
 def __init__(self):
     handlers = [
         (r"/", MainHandler),
         (r"/auth/login", WeiboAuthHandler),
         (r"/auth/logout", LogoutHandler),
         (r"/vote", VoteHandler),
     ]
     settings = dict(
         static_path=os.path.join(os.path.dirname(__file__), "public"),
         cookie_secret="__TODO:_GENERATE_YOUR_OWN_RANDOM_VALUE_HERE__",
         login_url="/auth/login",
         debug=True,
         xsrf_cookies=True,
         weibo_consumer_key='100689067',
         weibo_consumer_secret='1f54eff4858b924d090833d537335bd8',
         flash_policy_port = 843,
         flash_policy_file = op.join(ROOT, 'flashpolicy.xml'),
         socket_io_port = 8000,
     )
     VoteRouter = TornadioRouter(VoteConnection,
                         dict(enabled_protocols=['websocket', 'xhr-polling',
                                                 'jsonp-polling', 'htmlfile']))
     tornado.web.Application.__init__(self, VoteRouter.apply_routes(handlers), **settings)
     #self.redis = redis.StrictRedis()
     self.adb = opermongo.asyncdb(database='test')
     self.db = opermongo.db(database='test')
Пример #5
0
    def __init__(self):
        self.db = pymongo.Connection(port=settings.DB_PORT)[settings.DB_NAME]
        self.fs = GridFS(self.db)
        self.loader = Loader(
            os.path.join(ROOT_DIR, 'template'),
            autoescape=None,
            namespace={
                'static_url': lambda url: StaticFileHandler.make_static_url({'static_path': STATIC_DIR}, url),
                '_modules': ObjectDict({'Template': lambda template, **kwargs: self.loader.load(template).generate(**kwargs)}),
            },
        )

        router = TornadioRouter(ScribeConnection)
        router.app = self
        socketio = TornadoApplication(router.urls, app=self)
        self.connections = []

        class FooResource(Resource):
            def __call__(self, request):
                socketio(request)

            def __getitem__(self, name):
                return self

        Application.__init__(self, {
            '': HomeResource(self),
            'favicon.ico': StaticFileResource(os.path.join(STATIC_DIR, 'img', 'favicon.ico')),
            'sounds': EditsResource(self),
            'static': StaticFileResource(STATIC_DIR),
            'socket.io': FooResource(),
        })
Пример #6
0
def InitServer():
    if settings.LOGGING:
        logging.getLogger().setLevel(logging.DEBUG)
    generate_settings()
    SAHRouter = TornadioRouter(RouterConnection)
    SAHApplication = web.Application(
        SAHRouter.apply_routes(
            [
                (r"/", IndexHandler),
                (r"/test/", TestHandler),
                (
                    r"/static/(.*)",
                    web.StaticFileHandler,
                    {"path": os.path.abspath(os.path.join(os.getcwd(), "web", "static"))},
                ),
            ]
        ),
        socket_io_port=settings.WS_PORT,
        debug=settings.DEBUG,
    )
    SAHSocketServer = SocketServer(SAHApplication, auto_start=False)
    # Add periodic callback (aka faux-thread) into the ioloop before starting
    # Tornado doesn't respond well to running a thread while the IO loop is going.
    cb = ioloop.PeriodicCallback(GamePulse, 1000, SAHSocketServer.io_loop)
    cb.start()
    SAHSocketServer.io_loop.start()
Пример #7
0
def start_runner_server(project, runner, bind_address="", port_number=8001, http_username=None, http_password=None):
  if bind_address=="0.0.0.0":
    bind_address = ""

  SeesawConnection.project = project
  SeesawConnection.runner = runner

  runner.on_pipeline_start_item += SeesawConnection.handle_start_item
  runner.on_pipeline_finish_item += SeesawConnection.handle_finish_item
  runner.on_status += SeesawConnection.handle_runner_status

  router = TornadioRouter(SeesawConnection)

  application = AuthenticatedApplication(
    router.apply_routes([(r"/(.*\.(html|css|js|swf|png|ico))$",
                          web.StaticFileHandler, {"path": PUBLIC_PATH}),
                         ("/", IndexHandler),
                         ("/api/(.+)$", ApiHandler, {"runner": runner})]),
#   flash_policy_port = 843,
#   flash_policy_file = os.path.join(PUBLIC_PATH, "flashpolicy.xml"),
    socket_io_address = bind_address,
    socket_io_port = port_number,

    # settings for AuthenticatedApplication
    auth_enabled = (http_password or "").strip() != "",
    check_auth = lambda r, username, password: \
        (
          password==http_password and \
          (http_username or "").strip() in ["", username]
        ),
    auth_realm = "ArchiveTeam Warrior",
    skip_auth = [ r"^/socket\.io/1/websocket/[a-z0-9]+$" ]
  )

  SocketServer(application, auto_start=False)
Пример #8
0
def main(args=None):
    if args is None:
        args = sys.argv

    setup_logger()

    router = TornadioRouter(RouterConnection)

    bg_loop = IOLoop()
    bg_thread = Thread(target=lambda: bg_loop.start())
    bg_task = task.Task(bg_loop)

    application = Application(
        router.apply_routes([
            (r"/", IndexHandler),
            (r"/start", StartHandler),
            (r"/start_mission", StartMissionHandler),
        ]),
        debug=True,
    )

    application.listen(8000)

    StartHandler.triggered.connect(bg_task.setup_api)
    StartMissionHandler.triggered.connect(bg_task.start_mission)
    event.api_started.connect(RouterConnection.on_api_started)
    event.mission_started.connect(RouterConnection.on_mission_started)
    event.mission_result.connect(RouterConnection.on_mission_result)

    try:
        bg_thread.start()
        IOLoop.instance().start()
    except KeyboardInterrupt:
        bg_loop.stop()
        IOLoop.instance().stop()

    # api_token = args[1]

    # client_ = client.Client(api_token)
    # event_loop = tornado.ioloop.IOLoop()
    # event_loop = task.EventLoop()

    # mission = client.Mission(client=client_, event_loop=event_loop)
    # mission.start(api_deck_id=2, api_mission_id=5)
    # mission.start(api_deck_id=3, api_mission_id=21)
    # mission.start(api_deck_id=4, api_mission_id=38)

    # nyukyo = client.Nyukyo(client=client_, event_loop=event_loop)
    # nyukyo.start()

    # event_loop.start()

    return 0
Пример #9
0
 def __init__(self, state):
     router = TornadioRouter(Client)
     self.reportUUID = uuid.uuid4().hex
     self.app = tornado.web.Application(
         router.apply_routes([
           (r"/", MainHandler, dict(template='index.jade', reportUUID=self.reportUUID, state=state)),
           (r"/data\.json$", DataHandler, dict(reportUUID=self.reportUUID, state=state)),
           (r"/toplist\.json$", ResultsHandler, dict(reportUUID=self.reportUUID, state=state)),
         ]),
         template_path=os.path.join(os.path.dirname(__file__), "templates"),
         static_path=os.path.join(os.path.dirname(__file__), "static"),
         debug=True,
         )
Пример #10
0
def load_app(port, root):
    settings = {
        "static_path": path.join(root, "static"),
        "template_path": path.join(root, "template"),
        "globals": {
            "project_name": "BAT -- Bootstrap, AngularJS, Tornado"
        },
        "flash_policy_port": 843,
        "flash_policy_file": path.join(root, 'flashpolicy.xml'),
        "socket_io_port": port,
    }

    routers = [
        (r"/", MainHandler),
        (r"/ajax", AjaxHandler),
        (r"/signin", SigninHandler),
        (r"/fluid", FluidHandler),
        (r"/hero", HeroHandler),
        (r"/sfn", SFNHandler),
        (r"/sticky-footer", StickyFooterHandler),
        (r"/justified-nav", JustifiedNavHandler),
        (r"/carousel", CarouselHandler),
        (r"/market-narrow", MarketNarrowHandler),
        (r"/static-grid", StaticGridHandler),
        (r"/ajax-grid", AjaxGridHandler),
        (r"/angular-ui", AngularUIHandler),
        (r"/", SocketIOGenHandler)
    ]

    try:
        from tornadio2 import TornadioRouter, SocketServer
        from connections import QueryConnection
        # Create tornadio router
        QueryRouter = TornadioRouter(QueryConnection)
        # Create socket application
        application = web.Application(
            QueryRouter.apply_routes(routers),
            **settings
        )
        #application.listen(8888)
        SocketServer(application)
    except ImportError:
        print "Failed to load module tornadio2"
        application = web.Application(
            routers,
            **settings
        )
        application.listen(8888)
        tornado.ioloop.IOLoop.instance().start()
Пример #11
0
def start_warrior_server(warrior,
                         bind_address="",
                         port_number=8001,
                         http_username=None,
                         http_password=None):
    SeesawConnection.warrior = warrior

    warrior.on_projects_loaded += SeesawConnection.handle_projects_loaded
    warrior.on_project_refresh += SeesawConnection.handle_project_refresh
    warrior.on_project_installing += SeesawConnection.handle_project_installing
    warrior.on_project_installed += SeesawConnection.handle_project_installed
    warrior.on_project_installation_failed += SeesawConnection.handle_project_installation_failed
    warrior.on_project_selected += SeesawConnection.handle_project_selected
    warrior.on_status += SeesawConnection.handle_warrior_status
    warrior.runner.on_pipeline_start_item += SeesawConnection.handle_start_item
    warrior.runner.on_pipeline_finish_item += SeesawConnection.handle_finish_item
    warrior.runner.on_status += SeesawConnection.handle_runner_status

    if not http_username:
        http_username = warrior.http_username
    if not http_password:
        http_password = warrior.http_password

    ioloop.PeriodicCallback(SeesawConnection.broadcast_bandwidth, 1000).start()

    router = TornadioRouter(SeesawConnection)

    application = AuthenticatedApplication(
      router.apply_routes([(r"/(.*\.(html|css|js|swf|png|ico))$",
                            web.StaticFileHandler, {"path": PUBLIC_PATH}),
                           ("/", IndexHandler),
                           ("/api/(.+)$", ApiHandler, {"warrior": warrior})]),
        #   flash_policy_port = 843,
        #   flash_policy_file = os.path.join(PUBLIC_PATH, "flashpolicy.xml"),
      socket_io_address = bind_address,
      socket_io_port = port_number,

      # settings for AuthenticatedApplication
      auth_enabled = lambda: (realize(http_password) or "").strip() != "",
      check_auth = lambda r, username, password: \
          (
            password==realize(http_password) and \
            (realize(http_username) or "").strip() in ["", username]
          ),
      auth_realm = "ArchiveTeam Warrior",
      skip_auth = [ r"^/socket\.io/1/websocket/[a-z0-9]+$" ]
    )
    SocketServer(application, auto_start=False)
Пример #12
0
def run(port, address, debug):
    global ss
    logging.getLogger().setLevel(logging.DEBUG)
    router = TornadioRouter(ExecuteConnection)
    ss = SocketServer(web.Application(
                       router.apply_routes([(r"/", IndexHandler),
                                            (r"/static/(.*)", web.StaticFileHandler,
                                             {'path':'../static'}),
                                            ]),
                       socket_io_port = port,
                       socket_io_address = address, 
                       debug=debug),
              auto_start = False)

    ss.io_loop.add_handler(executor._fifo, handle_output, ss.io_loop.WRITE)
    ss.io_loop.start()
Пример #13
0
    def __init__(self, **settings):
        params = dict(enabled_protocols=["websocket", "xhr-polling", "jsonp-polling", "htmlfile"])
        router = TornadioRouter(handler.SocketIOHandler, params)
        handlers = router.apply_routes(
            [
                (r"/api/service", handler.ServiceHandler),
                (r"/api/store", handler.StoreHandler),
                (r"/options", handler.OptionsHandler),
                (r"/", handler.MainHandler),
            ]
        )
        tornado.web.Application.__init__(self, handlers, **settings)

        self.jinja = Environment(loader=FileSystemLoader(settings["template_path"]))
        tornado.locale.set_default_locale("en_US")
        self.locale = tornado.locale.get(locale.getdefaultlocale()[0])
        self.store = Store()
Пример #14
0
 def __init__(self, state):
     router = TornadioRouter(Client)
     self.reportUUID = uuid.uuid4().hex
     self.app = tornado.web.Application(
         router.apply_routes([
             (r"/", MainHandler,
              dict(template='index.jade',
                   reportUUID=self.reportUUID,
                   state=state)),
             (r"/data\.json$", DataHandler,
              dict(reportUUID=self.reportUUID, state=state)),
             (r"/toplist\.json$", ResultsHandler,
              dict(reportUUID=self.reportUUID, state=state)),
         ]),
         template_path=os.path.join(os.path.dirname(__file__), "templates"),
         static_path=os.path.join(os.path.dirname(__file__), "static"),
         debug=True,
     )
Пример #15
0
def start_warrior_server(warrior, bind_address="", port_number=8001, http_username=None, http_password=None):
  SeesawConnection.warrior = warrior

  warrior.on_projects_loaded += SeesawConnection.handle_projects_loaded
  warrior.on_project_refresh += SeesawConnection.handle_project_refresh
  warrior.on_project_installing += SeesawConnection.handle_project_installing
  warrior.on_project_installed += SeesawConnection.handle_project_installed
  warrior.on_project_installation_failed += SeesawConnection.handle_project_installation_failed
  warrior.on_project_selected += SeesawConnection.handle_project_selected
  warrior.on_status += SeesawConnection.handle_warrior_status
  warrior.runner.on_pipeline_start_item += SeesawConnection.handle_start_item
  warrior.runner.on_pipeline_finish_item += SeesawConnection.handle_finish_item
  warrior.runner.on_status += SeesawConnection.handle_runner_status

  if not http_username:
    http_username = warrior.http_username
  if not http_password:
    http_password = warrior.http_password

  ioloop.PeriodicCallback(SeesawConnection.broadcast_bandwidth, 1000).start()

  router = TornadioRouter(SeesawConnection)

  application = AuthenticatedApplication(
    router.apply_routes([(r"/(.*\.(html|css|js|swf|png|ico))$",
                          web.StaticFileHandler, {"path": PUBLIC_PATH}),
                         ("/", IndexHandler),
                         ("/api/(.+)$", ApiHandler, {"warrior": warrior})]),
#   flash_policy_port = 843,
#   flash_policy_file = os.path.join(PUBLIC_PATH, "flashpolicy.xml"),
    socket_io_address = bind_address,
    socket_io_port = port_number,

    # settings for AuthenticatedApplication
    auth_enabled = lambda: (realize(http_password) or "").strip() != "",
    check_auth = lambda r, username, password: \
        (
          password==realize(http_password) and \
          (realize(http_username) or "").strip() in ["", username]
        ),
    auth_realm = "ArchiveTeam Warrior",
    skip_auth = [ r"^/socket\.io/1/websocket/[a-z0-9]+$" ]
  )
  SocketServer(application, auto_start=False)
    def handle(self, *args, **options):
        if settings.DEBUG:
            import logging
            logger = logging.getLogger()
            logger.setLevel(logging.DEBUG)

        if len(args) > 1:
            raise CommandError('Usage is runserver_tornadio2 %s' % self.args)

        if len(args) == 1:
            port = args[0]
        else:
            port = settings.SOCKETIO_PORT

        # Setup event handlers
        for Cls in load_classes(settings.SOCKETIO_CLASSES):
            mixin(BaseSocket, Cls)

        os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
        wsgi_app = get_wsgi_application()
        app_handler = WSGIContainer(StaticFilesHandler(wsgi_app))
        router = TornadioRouter(
            BaseSocket,
            {'enabled_protocols': ['websocket', 'xhr-polling', 'htmlfile']})
        settings.SOCKETIO_GLOBALS['server'] = router.urls[0][2]['server']
        # A map of user IDs to their active connections.
        settings.SOCKETIO_GLOBALS['connections'] = defaultdict(set)
        application = Application(
            router.urls + [
                # Uncomment next line to handle static files through Tornado rather than Django or externally.
                #(r'/static/(.*)', StaticFileHandler, {'path': settings.STATICFILES_DIRS[0]}),
                (r'/admin$', RedirectHandler, {
                    'url': '/admin/',
                    'permanent': True
                }),
                # You probably want to comment out the next line if you have a login form.
                (r'/accounts/login/.*', RedirectHandler, {
                    'url': '/admin/',
                    'permanent': False
                }),
                (r'.*', FallbackHandler, {
                    'fallback': app_handler
                }),
            ],
            #flash_policy_port = 843,
            #flash_policy_file = 'flashpolicy.xml',  # TODO: Do we need this? TAA - 2012-03-07.
            socket_io_port=port,
            xsrf_cookies=False,
        )
        ssl_options = {
            'certfile': settings.SSL_CERTFILE,
            'keyfile': settings.SSL_KEYFILE,
        }
        SocketServer(application, ssl_options=ssl_options)
Пример #17
0
    def __init__(self):
        self.db = db
        self.config = config
        self.agent = AgentServer(application=self)

        settings = dict(
            template_path=os.path.join(os.path.dirname(__file__), "templates"),
            static_path=os.path.join(os.path.dirname(__file__), "static"),
            ui_modules={
                "Entry": EntryModule,
                "Sidebar": SidebarModule,
            },
            xsrf_cookies=False,
            cookie_secret="__TODO:_GENERATE_YOUR_OWN_RANDOM_VALUE_HERE__",
            login_url="/auth/login",
            debug=True,
            socket_io_port=8888,
        )

        from bcloud.handlers.host import HostHandler
        from bcloud.handlers.index import MainHandler
        from bcloud.handlers.websocket import PingConnection

        PingRouter = TornadioRouter(
            PingConnection,
            dict(enabled_protocols=[
                'websocket', 'xhr-polling', 'jsonp-polling', 'htmlfile'
            ]))
        handlers = PingRouter.apply_routes([
            (r"/hh(.*)", MainHandler, dict(database="hello")),
            (r"/host", HostHandler),
            # (r"/websocket", BCloudSocketHandler),
            # (r"/host", HostHandler),
            # (r"/entry/([^/]+)", EntryHandler),
            # (r"/compose", ComposeHandler),
            # (r"/auth/create", AuthCreateHandler),
            # (r"/auth/login", AuthLoginHandler),
            # (r"/auth/logout", AuthLogoutHandler),
        ])

        super(Application, self).__init__(handlers, **settings)
Пример #18
0
def main():
    print "Server IP Address:", GetMyIPAddr()

    # Create TornadIO2 router
    router = TornadioRouter(ChatConnection)

    # Create Tornado application with urls from router
    app = web.Application(router.urls,
                          socket_io_port=CONFIG.PORT,
                          flash_policy_file='flashpolicy.xml')

    SocketServer(app)
Пример #19
0
def start_runner_server(project,
                        runner,
                        bind_address="",
                        port_number=8001,
                        http_username=None,
                        http_password=None):
    if bind_address == "0.0.0.0":
        bind_address = ""

    SeesawConnection.project = project
    SeesawConnection.runner = runner

    runner.on_pipeline_start_item += SeesawConnection.handle_start_item
    runner.on_pipeline_finish_item += SeesawConnection.handle_finish_item
    runner.on_status += SeesawConnection.handle_runner_status

    router = TornadioRouter(SeesawConnection)

    application = AuthenticatedApplication(
      router.apply_routes([(r"/(.*\.(html|css|js|swf|png|ico))$",
                            web.StaticFileHandler, {"path": PUBLIC_PATH}),
                           ("/", IndexHandler),
                           ("/api/(.+)$", ApiHandler, {"runner": runner})]),
        #   flash_policy_port = 843,
        #   flash_policy_file = os.path.join(PUBLIC_PATH, "flashpolicy.xml"),
      socket_io_address = bind_address,
      socket_io_port = port_number,

      # settings for AuthenticatedApplication
      auth_enabled = (http_password or "").strip() != "",
      check_auth = lambda r, username, password: \
          (
            password==http_password and \
            (http_username or "").strip() in ["", username]
          ),
      auth_realm = "ArchiveTeam Warrior",
      skip_auth = [ r"^/socket\.io/1/websocket/[a-z0-9]+$" ]
    )

    SocketServer(application, auto_start=False)
Пример #20
0
def load_app(port, root):
    settings = {
        "static_path": path.join(root, "static"),
        "template_path": path.join(root, "template"),
        "globals": {
            "project_name": "BAT -- Bootstrap, AngularJS, Tornado"
        },
        "flash_policy_port": 843,
        "flash_policy_file": path.join(root, 'flashpolicy.xml'),
        "socket_io_port": port,
    }

    routers = [(r"/", MainHandler), (r"/ajax", AjaxHandler),
               (r"/signin", SigninHandler), (r"/fluid", FluidHandler),
               (r"/hero", HeroHandler), (r"/sfn", SFNHandler),
               (r"/sticky-footer", StickyFooterHandler),
               (r"/justified-nav", JustifiedNavHandler),
               (r"/carousel", CarouselHandler),
               (r"/market-narrow", MarketNarrowHandler),
               (r"/static-grid", StaticGridHandler),
               (r"/ajax-grid", AjaxGridHandler),
               (r"/angular-ui", AngularUIHandler),
               (r"/gen", SocketIOGenHandler)]

    try:
        from tornadio2 import TornadioRouter, SocketServer
        from connections import QueryConnection
        # Create tornadio router
        QueryRouter = TornadioRouter(QueryConnection)
        # Create socket application
        application = web.Application(QueryRouter.apply_routes(routers),
                                      **settings)
        #application.listen(8888)
        SocketServer(application)
    except ImportError:
        print "Failed to load module tornadio2"
        application = web.Application(routers, **settings)
        application.listen(port)
        tornado.ioloop.IOLoop.instance().start()
Пример #21
0
def start_runner_server(project, runner, bind_address="", port_number=8001):
  if bind_address=="0.0.0.0":
    bind_address = ""

  SeesawConnection.project = project
  SeesawConnection.runner = runner

  runner.on_pipeline_start_item += SeesawConnection.handle_start_item
  runner.on_pipeline_finish_item += SeesawConnection.handle_finish_item
  runner.on_status += SeesawConnection.handle_runner_status

  router = TornadioRouter(SeesawConnection)
  application = web.Application(
    router.apply_routes([(r"/(.*\.(html|css|js|swf|png))$",
                          web.StaticFileHandler, {"path": PUBLIC_PATH}),
                         ("/", IndexHandler),
                         ("/api/(.+)$", ApiHandler, {"runner": runner})]),
#   flash_policy_port = 843,
#   flash_policy_file = os.path.join(PUBLIC_PATH, "flashpolicy.xml"),
    socket_io_address = bind_address,
    socket_io_port = port_number
  )
  SocketServer(application, auto_start=False)
Пример #22
0
def run(port, address, debug):
    if debug:
        logging.getLogger().setLevel(logging.DEBUG)
    router = TornadioRouter(ExecuteConnection)
    ss = SocketServer(web.Application(
                       router.apply_routes([(r"/", IndexHandler),
                                            (r"/static/(.*)", web.StaticFileHandler,
                                             {'path':os.path.join(ROOT ,'static')}),
                                            ]),
                       flash_policy_port = 843,
                       flash_policy_file = os.path.join(ROOT, 'flashpolicy.xml'),
                       socket_io_port = port,
                       socket_io_address = address, 
                       debug=debug),
              auto_start = False)

    # We do auto_start=False above and the following loop, so that SIGINT interrupts from
    # the user doesn't kill the process.
    while True:
        try:
            ss.io_loop.start()
        except:
            pass
Пример #23
0
 def __init__(self, debug_):
     settings = dict(
         template_path=os.path.join(os.path.dirname(__file__), "templates"),
         static_path=os.path.join(os.path.dirname(__file__), "static"),
         login_url="/auth/login",
         debug=debug_,
         socket_io_port=options.port,
         enabled_protocols=['websocket', 'xhr-multipart', 'xhr-polling'],
     )
     handlers = [
         (r"/", IndexHandler),
         (r"/toggleSample", ToggleSample),
         (r"/echo", EchoHandler),
         (r"/socket.io.js", SocketIOHandler),
     ]
     socketServer = TornadioRouter(RootSocketConnection, settings)
     handlers.extend(socketServer.urls)
     tornado.web.Application.__init__(self, handlers, **settings)
Пример #24
0
def run(project_root):
    serverurls = []
    servermodels = []

    # add Airy static file handler
    serverurls.extend([(r"/airy/form/", web.FormProcessor),
                       (r"/airy/(.*)", tornado.web.StaticFileHandler, {
                           "path": os.path.join(AIRY_ROOT, 'static')
                       })])

    # add Airy core handler
    core_router = TornadioRouter(web.AiryCoreHandler, settings.__dict__)
    serverurls.extend(core_router.urls)

    # add application handlers
    for appname in settings.installed_apps:
        # add app urls
        appurls = __import__('%s.urls' % appname,
                             fromlist=['%s.url' % appname])
        urlpatterns = getattr(appurls, 'urlpatterns')
        serverurls.extend(urlpatterns)
        try:
            models = __import__('%s.models' % appname,
                                fromlist=['%s.models' % appname])
            servermodels.append(models)
        except ImportError:
            pass

    # restart on code change
    for root, dirs, files in os.walk(settings.template_path):
        for x in files:
            if os.path.splitext(x)[1].lower() == '.html':  # track templates
                autoreload._watched_files.add(os.path.join(root, x))

    application = tornado.web.Application(serverurls, **settings.__dict__)
    settings.application = web.site.application = application
    web.site.loader = template.Loader(settings.template_path)

    SocketServer(application)
Пример #25
0
def main():
    import threading
    t = threading.Thread(target=redis_listener)
    t.setDaemon(True)
    t.start()

    LookupsServer = TornadioRouter(LookupsConnection)
    # Fill your routes here
    routes = []
    # Extend list of routes with Tornadio2 URLs
    routes.extend(LookupsServer.urls)

    tornado.options.parse_command_line()
    if options.debug:
        logging.getLogger().setLevel(logging.DEBUG)
    else:
        logging.getLogger().setLevel(logging.INFO)

    application = tornado.web.Application(routes, socket_io_port=options.port)
    try:
        SocketServer(application)
    except KeyboardInterrupt:
        pass
Пример #26
0
    def send_notification(self, x):
        if(type(x) == dict):
            self.emit('notification', json.dumps(x, cls=MongoAwareEncoder))

    @gen.coroutine
    @event
    def notification_read(self, _id):
        db = self.db
        notif_coll = db["notif_" + self.get_current_user()['id']]
        res = yield motor.Op(notif_coll.find_one, {'_id': objectid.ObjectId(_id)})
        yield motor.Op(notif_coll.update, {'from': res['from']}, {"$set": {'read': True}}, multi=True)

    @event
    def disconnect(self, *args, **kwargs):
        print "on_disconnect"

    @event
    def disconnected(self, *args, **kwargs):
        print "on_disconnected"

    def on_close(self, *args, **kwargs):
        try:
            self.notif_checker.stop()
        except:
            pass


MyRouter = TornadioRouter(MyConnection)
mappings = MyRouter.apply_routes(mappings)
Пример #27
0
            fileinfo = self.request.files['filearg'][0]

            fname = fileinfo['filename']
            fh = open("static/pic/" + fname, 'w')
            fh.write(fileinfo['body'])
            fh.close()

            im = Image.open("static/pic/" + fname)
            im.save('static/pic/' + fname)

            response['status'] = True
            response['path'] = "pic/" + fname
            self.finish(
                json.dumps(response))

EventRouter = TornadioRouter(
    EventConnection)



application = tornado.web.Application(
    EventRouter.apply_routes([
        (r"/", NotVJSHandler.Index),
        (r"/pic/(.*)", tornado.web.StaticFileHandler, {
            'path': path.join(static_path, "pic")}),
        (r"/temp/(.*)", tornado.web.StaticFileHandler, {
            'path': path.join(static_path, "temp")}),
        (r"/js/(.*)", tornado.web.StaticFileHandler, {
            'path': path.join(static_path, "js")}),
        (r"/css/(.*)", tornado.web.StaticFileHandler, {
            'path': path.join(static_path, "css")}),
        (r"/upload$", NotVJSHandler.Upload)]),
Пример #28
0
        ChatConnection.no_name.add(self)

    def on_close(self):
        print 'client disconnected'
        if self in ChatConnection.participants:
            del ChatConnection.participants[self]

    def on_message(self, msg):
        print "Putting %s in correct lobby" % msg
        ChatConnection.participants[msg.lower()] = self
        if self in ChatConnection.no_name:
            ChatConnection.no_name.remove(self)


# Create chat server
ChatRouter = TornadioRouter(ChatConnection, dict(websocket_check=True))


# Create socket application
application = tornado.web.Application(
    ChatRouter.apply_routes([(r'/', IndexHandler),
                           (r'/socket.io/socket.io.js', SocketIOHandler)]),
    socket_io_port = 8001
)

if __name__ == '__main__':
    import logging
    logging.getLogger().setLevel(logging.DEBUG)

    # Create and start tornado server
    SocketServer(application)
Пример #29
0
    def on_delete(self, model, options):
        raise NotImplementedError


class IndexHandler(RequestHandler):
    def get(self):
        self.render("static/test.html")


class SocketIOHandler(RequestHandler):
    def get(self):
        self.render("static/socket.io.js")


SyncRouter = TornadioRouter(BackboneConnection)


sio_application = Application(
    SyncRouter.apply_routes([
        (r"/socket.io.js", SocketIOHandler)
    ]),
    socket_io_port = 8001
)

web_application = Application([
    (r"/", IndexHandler),
    (r"/(.*)", tornado.web.StaticFileHandler, {"path": "static"})
])

if __name__ == "__main__":
Пример #30
0
    """Serve the index file"""
    def get(self):
        self.render(ROOT_DIR + '/new.html')

class RouterConnection(SocketConnection):
    __endpoints__ = {'/game': GameConnection}

    def on_open(self, info):
        pass  
        

                       


# Create tornadio server
jazzyRouter = TornadioRouter(RouterConnection)

# Create socket application
application = web.Application(
    jazzyRouter.apply_routes([(r"/", IndexHandler),
                              (r"/(.*\.(js|html|css|ico|gif|jpe?g|png|ogg|mp3))", web.StaticFileHandler, {"path": ROOT_DIR}),
                              (r"/([^(socket.io)].*)", HTTPJSONHandler)]),
    flash_policy_port = 843,
    flash_policy_file = op.join(ROOT_DIR, '/other/flashpolicy.xml'),
    socket_io_port = PORT_NUMBER,
    debug=True
)
        
if __name__ == "__main__":
    # prepare for the first games to be started 
    gamePool = GamePool()
Пример #31
0
from tornado import web
from tornadio2 import SocketConnection, TornadioRouter, SocketServer


# Declare connection class
class MyConnection(SocketConnection):
    def on_open(self, info):
        print('Client connected')

    def on_message(self, msg):
        print('Got', msg)
        self.send(msg)

    def on_close(self):
        print('Client disconnected')


# Create TornadIO2 router
router = TornadioRouter(MyConnection)

# Create Tornado application with urls from router
app = web.Application(router.urls, socket_io_port=8001)

# Start server
if __name__ == '__main__':
    SocketServer(app)
Пример #32
0
    def on_open(self, info):
        print 'Router', repr(info)


if __name__ == "__main__":
    tornado.options.define('appid', default='165', help='RMonitor AppID')
    tornado.options.parse_command_line()

    # Create RaceMonitor client
    rm = rmonitor.RMonitorClient(tornado.options.options.appid)
    #rm = rmonitor.RMonitorFile('race.log')
    session = Session(rm)

    # Create tornadio server
    MyRouter = TornadioRouter(RouterConnection)

    # Create socket application
    application = web.Application(MyRouter.apply_routes([
        (r"/", IndexHandler),
        (r"/data.json", DataHandler),
        (r"/.*js", FileHandler),
        (r"/.*css", FileHandler),
        (r"/.*gif", FileHandler),
    ]),
                                  flash_policy_port=8843,
                                  flash_policy_file=op.join(
                                      ROOT, 'flashpolicy.xml'),
                                  socket_io_port=8001,
                                  verify_remote_ip=False)
Пример #33
0
        self.send(message)


class RouterConnection(SocketConnection):
    __endpoints__ = {
        '/chat': ChatConnection,
        '/ping': PingConnection,
        '/gs': GSConnection
    }

    def on_open(self, info):
        print 'Router', repr(info)


# Create tornadio server
MyRouter = TornadioRouter(RouterConnection)

# Create socket application
application = web.Application(
    MyRouter.apply_routes([
        (r"/", IndexHandler),
        (r"/socket.io.js", SocketIOHandler),
        (r"/login", GoogleHandler),
        (r"/getDeck/([0-9a-f]+)", DecksListHandler),
        (r"/getTokens/([0-9a-f]+)", TokenListHandler),
        (r"/getCard/([0-9]+)", getCardHandler),
        (r"/getAToken/([0-9]+)", getTokenHandler),
    ]),
    #flash_policy_port = 843,
    #flash_policy_file = op.join(ROOT, 'flashpolicy.xml'),
    cookie_secret=my_cookie_secret,
Пример #34
0
                  'elapsedTime': time.time() - start_time }
      } )

# We setup our connection handler. You can define different endpoints
# for additional socket.io services.
class RouterConnection(SocketConnection):
    __endpoints__ = {
                      '/cat': MinimalConnection
                    }

    def on_open(self, info):
      pass


# Create tornadio router
MinimalRouter = TornadioRouter(RouterConnection)

### cmd-line parsing and server init ###

if __name__ == "__main__":
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('--port', help='server port to bind to, default: 9999', type=int, default=9999)
    parser.add_argument('--mt-host', help='host of the mt server (server.py), default '+mt_host, default=mt_host)
    parser.add_argument('--mt-port', help='port of the mt server (server.py), default '+str(mt_port), type=int, default=mt_port)
    parser.add_argument('--biconcor-model', help='model file for bilingual concordancer')
    parser.add_argument('--biconcor-cmd', help='command binary for bilingual concordancer')
    parser.add_argument('--log-dir', help='directory for log files', default=".")
    settings = parser.parse_args(sys.argv[1:])
    mt_host = settings.mt_host
    mt_port = settings.mt_port
Пример #35
0
class WebSocketHandler(SocketConnection):
    """
    Manages the global list of subscribers.
    """
    def on_open(self, *args, **kwargs):
        SUBSCRIBERS.append(self)

    def on_close(self):
        if self in SUBSCRIBERS:
            SUBSCRIBERS.remove(self)


# Create tornadio router
WSRouter = TornadioRouter(
    WebSocketHandler,
    dict(enabled_protocols=[
        'websocket', 'xhr-polling', 'jsonp-polling', 'htmlfile'
    ]))

# Create socket application
application = web.Application(
    WSRouter.apply_routes([(r"/step-(\d)+[/]?", StepPageHandler)]),
    flash_policy_port=843,
    flash_policy_file=os.path.join(ROOT, 'flashpolicy.xml'),
    template_path=os.path.join(ROOT, 'templates'),
    static_path=os.path.join(ROOT, 'static'),
    socket_io_port=8001,
    enable_pretty_logging=True)

if __name__ == '__main__':
    socketio_server = SocketServer(application, auto_start=False)
Пример #36
0
import os
import logging

from tornadio2 import TornadioRouter, SocketServer
from tornado import web

os.environ['DJANGO_SETTINGS_MODULE'] = 'example.settings'

from django_socketio_chat.tornadio_app import chat
from django.conf import settings
logging.getLogger().setLevel(logging.INFO)

# Create chat router
ChatRouter = TornadioRouter(chat.ChatConnection,
                            user_settings={'websocket_check': True},
                            namespace='chat/socket.io')

# Create application
application = web.Application(
    ChatRouter.apply_routes([]),
    socket_io_port=8001,
    debug=settings.DEBUG
)

SocketServer(application)

  @timer('delete_plugins')
  def delete_plugins(self):
    self.tokenizer_factory.deleteInstance(self.tokenizer);
    self.tokenizer_plugin.destroy(self.tokenizer_factory)
    self.tokenizer, self.tokenizer_factory = None, None
    del self.tokenizer_plugin
  
    self.htr_factory.deleteInstance(self.htr);
    self.htr_plugin.destroy(self.htr_factory)
    self.htr, self.htr_factory = None, None
    del self.htr_plugin
  


# Create tornadio router
CasmacatRouter = TornadioRouter(RouterConnection)


if __name__ == "__main__":
    from sys import argv
    import logging
    import atexit
    import getopt 

    try:
      opts, args = getopt.getopt(sys.argv[1:], "hl:c:", ["help", "logfile=", "config="])
    except getopt.GetoptError as err:
      # print help information and exit:
      print >> sys.stderr, str(err) # will print something like "option -a not recognized"
      usage()
      sys.exit(2)
Пример #38
0
from tornadio2 import TornadioRouter

from cloudtunes.realtime import frontend

from .connection import SocketConnection

ENABLED_CHANNELS = {
    frontend.RemoteControlChannel,
    frontend.ModelChannel,
    frontend.PlayerChannel,
    frontend.SyncChannel,
}

# Install endpoints.
SocketConnection.__endpoints__ = {
    '/' + channel.namespace: channel
    for channel in ENABLED_CHANNELS
}

router = TornadioRouter(SocketConnection)
Пример #39
0
    url(r"/", HomeHandler, name="home"),
    url(r'/accounts/login', LoginHandler, name="login"),
    url(r'/accounts/register', RegisterHandler, name="register"),
    url(r'/accounts/logout', LogoutHandler, name="logout"),
    url(r'/accounts/check_username_availability/(.+)/',
        UserNameAvailabilityHandler, name="user_name_avaliability"),

    url(r'/accounts/profile', FakeHandler, name="profile"),  # TODO
    url(r'/accounts/settings', FakeHandler, name="settings"),  # TODO

    # ajax api
    url(r'/v1/dropbox/get_tree/', DropboxGetTree, name="dropbox_get_path"),
    url(r'/v1/dropbox/get_file/', DropboxGetFile, name="dropbox_get_file"),
    url(r'/v1/dropbox/save_file/', DropboxSaveFile, name="dropbox_save_file"),
    url(r'/v1/dropbox/create_dir/', DropboxCreateDir, name="dropbox_create_dir"),
    url(r'/v1/dropbox/delete/', DropboxDelete, name="dropbox_delete"),
    url(r'/v1/dropbox/move/', DropboxMove, name="dropbox_move"),
    url(r'/v1/dropbox/copy/', DropboxSave, name="dropbox_copy"),
]

if options.debug:
    url_patterns += [
        url(r'/trash_debug/(.*)', RenderTrashHtml, name="trash_debug"),
    ]

if options.socketio:
    from tornadio2 import TornadioRouter
    from handlers.socketio import EdtrConnection
    EdtrRouter = TornadioRouter(EdtrConnection)
    url_patterns = EdtrRouter.apply_routes(url_patterns)
Пример #40
0
        
        token = uuid.uuid4().hex
        session_store.put(token, id)
        self.set_cookie('id', token, httponly=True)
        
        session.conn.emit("authed", {
            "success": True
        })


class SocketIOHandler(RequestHandler):
    def get(self):
        self.render("socket.io.js")


Router = TornadioRouter(SocketIOConnection)
session_store = SessionStore(Router)

application = Application(
    Router.apply_routes([
        (r"/socket.io.js", SocketIOHandler),
        (r"/jquery-1.8.2.min.js", JQHandler),
        (r"/login", LoginPageHandler),
        (r"/", IndexHandler)
    ]),
    socket_io_port = 8888
)

if __name__ == "__main__":
    import logging
    logging.getLogger().setLevel(logging.DEBUG)
Пример #41
0
import views
from tornadio2 import TornadioRouter, SocketConnection
import tornadoredis

class tornadioConnection(SocketConnection):
	__endpoints__ = {
		'/tornado/stream': views.StreamComm,
	}

socketIORouter = TornadioRouter(
	tornadioConnection, {
		'enabled_protocols': [
			'websocket',
			'xhr-polling',
			'jsonp-polling'
		]
	}
)

urls = socketIORouter.apply_routes([])
Пример #42
0

if __name__ == "__main__":
  try:
    print('Started Freeciv-proxy. Use Control-C to exit');
 
    if len(sys.argv) == 2:
      PROXY_PORT = int(sys.argv[1]);
    print('port: ' + str(PROXY_PORT));
 
    LOG_FILENAME = '/tmp/logging' +str(PROXY_PORT) + '.out'
    #logging.basicConfig(filename=LOG_FILENAME,level=logging.INFO)
    logging.basicConfig(level=logging.INFO)
    logger = logging.getLogger("freeciv-proxy");

    CivRouter = TornadioRouter(CivConnection,
                               dict(enabled_protocols = ['websocket']));

    application = web.Application( 
        CivRouter.apply_routes([(r"/", IndexHandler),
                                (r"/status", StatusHandler, dict(router=CivRouter))]),
        socket_io_port = PROXY_PORT
    )

    # Create and start tornadio server
    SocketServer(application);
  except KeyboardInterrupt:
    print('Exiting...');



Пример #43
0

class WebSocketHandler(SocketConnection):
    """
    Manages the global list of subscribers.
    """
    def on_open(self, *args, **kwargs):
        SUBSCRIBERS.append(self)

    def on_close(self):
        if self in SUBSCRIBERS:
            SUBSCRIBERS.remove(self)

# Create tornadio router
WSRouter = TornadioRouter(WebSocketHandler,
                            dict(enabled_protocols=['websocket', 'xhr-polling',
                                                    'jsonp-polling', 'htmlfile']))

# Create socket application
application = web.Application(
    WSRouter.apply_routes([(r"/step-(\d)+[/]?", StepPageHandler)]),
    flash_policy_port = 843,
    flash_policy_file = os.path.join(ROOT, 'flashpolicy.xml'),
    template_path = os.path.join(ROOT, 'templates'),
    static_path = os.path.join(ROOT, 'static'),
    socket_io_port = 8001,
    enable_pretty_logging = True
)

if __name__ == '__main__':
    socketio_server = SocketServer(application, auto_start=False)
Пример #44
0

class ChatConnection(tornadio2.conn.SocketConnection):
    # Class level variable
    participants = set()

    def on_open(self, info):
        print 'client connected'
        self.participants.add(self)

    def on_close(self):
        print 'client disconnected'
        self.participants.remove(self)


# Create chat server
ChatRouter = TornadioRouter(ChatConnection, dict(websocket_check=True))

# Create socket application
application = tornado.web.Application(ChatRouter.apply_routes([
    (r"/", IndexHandler), (r"/socket.io/socket.io.js", SocketIOHandler)
]),
                                      socket_io_port=8001)

if __name__ == "__main__":
    import logging
    logging.getLogger().setLevel(logging.DEBUG)

    # Create and start tornadio server
    SocketServer(application)
Пример #45
0
        message['server'] = [now.hour, now.minute, now.second, now.microsecond / 1000]
        self.send(message)


class RouterConnection(SocketConnection):
    __endpoints__ = {'/chat': ChatConnection,
                     '/ping': PingConnection,
                     '/gs': GSConnection}

    def on_open(self, info):
        print 'Router', repr(info)


# Create tornadio server
MyRouter = TornadioRouter(RouterConnection)

# Create socket application
application = web.Application(
        MyRouter.apply_routes([(r"/", IndexHandler),
        (r"/socket.io.js", SocketIOHandler),
        (r"/login", GoogleHandler),
        (r"/getDeck/([0-9a-f]+)", DecksListHandler),
        (r"/getTokens/([0-9a-f]+)", TokenListHandler),
        (r"/getCard/([0-9]+)", getCardHandler),
        (r"/getAToken/([0-9]+)", getTokenHandler),
    ]),
    #flash_policy_port = 843,
    #flash_policy_file = op.join(ROOT, 'flashpolicy.xml'),
    cookie_secret=my_cookie_secret,
    static_path=os.path.join(os.path.dirname(__file__), "static"),
Пример #46
0
        return data, [now.hour, now.minute, now.second, now.microsecond / 1000]

    @event
    def stats(self):
        print self.session.server.stats.dump()
        return self.session.server.stats.dump()


# Create tornadio router
PingRouter = TornadioRouter(
    PingConnection,
    dict(
        enabled_protocols=[
            'websocket',
            'xhr-polling',
            'jsonp-polling',
            'htmlfile'
        ]
    )
)

# Create socket application
application = web.Application(
    PingRouter.apply_routes(
        [
            (r"/", IndexHandler),
            (r"/stats", StatsHandler),
            (r"/socket.io.js", SocketIOHandler)
        ]
    ),
Пример #47
0
import os
import logging

from tornadio2 import TornadioRouter, SocketServer
from tornado import web

os.environ['DJANGO_SETTINGS_MODULE'] = 'example.settings'

from django_socketio_chat.tornadio_app import chat
from django.conf import settings
logging.getLogger().setLevel(logging.INFO)

# Create chat router
ChatRouter = TornadioRouter(chat.ChatConnection,
                            user_settings={'websocket_check': True},
                            namespace='chat/socket.io')

# Create application
application = web.Application(ChatRouter.apply_routes([]),
                              socket_io_port=8001,
                              debug=settings.DEBUG)

SocketServer(application)
Пример #48
0
        self.send({'action':'speed','speed':self.user.getSpeed()})
    '''
    def on_message(self, message):
        if not self.id:
            if message.find(self.accesskey):
                self.id = message
                self.user=User(self.id)
                self.clients.add(self)
    '''





# Create tornadio router
PingRouter = TornadioRouter(PingConnection)

# Create socket application
application = web.Application(
     PingRouter.apply_routes([]),

    flash_policy_port = 843,
    flash_policy_file = op.join(ROOT, 'flashpolicy.xml'),
    socket_io_port = 8001
)

if __name__ == "__main__":
  
    logging.getLogger().setLevel(logging.DEBUG)

    # Create and start tornadio server
Пример #49
0
        Thread.__init__(self)
        self.daemon = True
        self.civcom = civcom
        self.ws_connection = ws_connection

    def run(self):
        while 1:
            if (self.civcom.stopped): return

            packet = self.civcom.get_send_result_string()
            if (len(packet) > 4):
                self.ws_connection.send(packet)
            time.sleep(WS_UPDATE_INTERVAL)


CivRouter = TornadioRouter(CivConnection)

application = web.Application(CivRouter.urls,
                              enabled_protocols=[
                                  'websocket', 'flashsocket', 'xhr-multipart',
                                  'xhr-polling'
                              ],
                              flash_policy_port=843,
                              flash_policy_file=op.join(
                                  ROOT, 'flashpolicy.xml'),
                              socket_io_port=8002)

if __name__ == "__main__":
    import logging
    logging.getLogger().setLevel(level=logging.INFO)
Пример #50
0
    def __init__(self,
                 cacher,
                 addr,
                 port,
                 log_dir_path,
                 log_level=logging.DEBUG):
        def log_path(name):
            path = os.path.join(log_dir_path, name)
            if os.path.exists(path):
                os.unlink(path)
            return path

        router = TornadioRouter(Client)
        self.cacher = cacher
        self.reportUUID = uuid.uuid4().hex
        self.app = tornado.web.Application(
            router.apply_routes([
                (r"/", MainHandler,
                 dict(template='index.jade',
                      reportUUID=self.reportUUID,
                      cacher=cacher)),
                (r"/offline\.html", MainHandler,
                 dict(template='offline.jade',
                      reportUUID=self.reportUUID,
                      cacher=cacher)),
                (r"/brief\.html$", MainHandler,
                 dict(template='brief.jade',
                      reportUUID=self.reportUUID,
                      cacher=cacher)),
                (r"/monitoring\.html$", MainHandler,
                 dict(template='monitoring.jade',
                      reportUUID=self.reportUUID,
                      cacher=cacher)),
                (r"/data\.json$", JsonHandler,
                 dict(reportUUID=self.reportUUID, cacher=cacher)),
            ]),
            template_path=os.path.join(os.path.dirname(__file__), "templates"),
            static_path=os.path.join(os.path.dirname(__file__), "static"),
            socket_io_port=port,
            socket_io_address=addr,
            debug=True,
            autoreload=False)

        self.access_log = None
        self.app_log = None
        self.gen_log = None

        if log_dir_path:
            self.access_log = logging.getLogger("tornado.access")
            self.access_log.setLevel(log_level)
            access_handler = logging.FileHandler(log_path("access.log"))
            self.access_log.addHandler(access_handler)

            self.app_log = logging.getLogger("tornado.application")
            self.app_log.setLevel(log_level)
            app_handler = logging.FileHandler(log_path("app.log"))
            templ = "%(asctime)s: [%(levelname)s]: %(message)s"
            app_handler.setFormatter(logging.Formatter(templ))
            self.app_log.addHandler(app_handler)

            self.gen_log = logging.getLogger("tornado.general")
            self.gen_log.setLevel(log_level)
            gen_handler = logging.FileHandler(log_path("general.log"))
            self.gen_log.addHandler(gen_handler)
Пример #51
0
        self.render('index.html')


class SocketIOHandler(web.RequestHandler):
    def get(self):
        self.render('../socket.io.js')


class PingConnection(SocketConnection):
    @event
    def ping(self, client):
        now = datetime.datetime.now()
        return client, [now.hour, now.minute, now.second, now.microsecond / 1000]

# Create tornadio router
PingRouter = TornadioRouter(PingConnection)

# Create socket application
application = web.Application(
    PingRouter.apply_routes([(r"/", IndexHandler),
                           (r"/socket.io.js", SocketIOHandler)]),
    flash_policy_port = 843,
    flash_policy_file = op.join(ROOT, 'flashpolicy.xml'),
    socket_io_port = 8001
)

if __name__ == "__main__":
    import logging
    logging.getLogger().setLevel(logging.DEBUG)

    # Create and start tornadio server
Пример #52
0
    def handle(self, *args, **options):
        if settings.DEBUG:
            logger.setLevel(logging.DEBUG)

        if len(args) > 1:
            raise CommandError('Usage is runserver_tornadio2 %s' % self.args)

        if len(args) == 1:
            if ':' in args[0]:
                addr, port = args[0].split(':')
            else:
                port = args[0]
        else:
            port = getattr(settings, 'SOCKETIO_PORT', 8000)

        # Setup event handlers
        for Cls in load_classes(getattr(settings,'SOCKETIO_CLASSES', [])):
            mixin(BaseSocket, Cls)

        os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings')
        wsgi_app = get_wsgi_application()
        app_handler = WSGIContainer(StaticFilesHandler(wsgi_app))
        router = TornadioRouter(BaseSocket, {
            'enabled_protocols': [
                'websocket',
                'xhr-polling',
                'htmlfile'
            ]})

        if not hasattr(settings, 'SOCKETIO_GLOBALS'):
            settings.SOCKETIO_GLOBALS = {}

        settings.SOCKETIO_GLOBALS['server'] = router.urls[0][2]['server']
        # A map of user IDs to their active connections.
        settings.SOCKETIO_GLOBALS['connections'] = defaultdict(set)

        tornado_routes = []
        for url, path in getattr(settings, 'SOCKETIO_ROUTES', []):
            cls = _get_class(path, object)
            tornado_routes.append((url, cls))

        application = Application(
            router.urls + tornado_routes + [
                # Uncomment next line to handle static files through Tornado rather than Django or externally.
                #(r'/static/(.*)', StaticFileHandler, {'path': settings.STATICFILES_DIRS[0]}),
                #(r'/admin$', RedirectHandler, {'url': '/admin/', 'permanent': True}),
                # You probably want to comment out the next line if you have a login form.
                #(r'/accounts/login/.*', RedirectHandler, {'url': '/admin/', 'permanent': False}),
                (r'.*', FallbackHandler, {'fallback': app_handler}),
            ],
            #flash_policy_port = 843,
            #flash_policy_file = 'flashpolicy.xml',  # TODO: Do we need this? TAA - 2012-03-07.
            socket_io_port = port,
            xsrf_cookies = False,
            debug = settings.DEBUG
        )
        ssl_options = getattr(settings, 'SOCKETIO_SSL_OPTIONS', {})
        if ssl_options:
            SocketServer(application, ssl_options = ssl_options)
        else:
            SocketServer(application)