def serve(self): def run_server(server): tornado.ioloop.IOLoop.instance().start() self.server = SocketServer(self.app, auto_start=False) th = Thread(target=run_server, args=(self.server, )) th.start()
def serve(self): def run_server(server): server.start() self.server = SocketServer(self.app, auto_start = False) th = Thread(target=run_server, args=(self.server,)) th.start()
class ReportServer(object): def __init__(self, cacher): 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"), debug=True, ) def serve(self): def run_server(server): tornado.ioloop.IOLoop.instance().start() self.server = SocketServer(self.app, auto_start=False) th = Thread(target=run_server, args=(self.server,)) th.start() def stop(self): self.server.stop() def send(self, data): for connection in Client.CONNECTIONS: data['uuid'] = self.reportUUID connection.send(json.dumps(data)) def reload(self): for connection in Client.CONNECTIONS: connection.emit('reload') def render_offline(self): loader = template.Loader( os.path.join(os.path.dirname(__file__), "templates")) cached_data = { 'data': self.cacher.get_all_data(), 'uuid': self.reportUUID, } return loader.load('offline.jade').generate(cached_data=json.dumps(cached_data))
def serve(self): def run_server(server): tornado.ioloop.IOLoop.instance().start() self.server = SocketServer(self.app, auto_start=False) th = Thread(target=run_server, args=(self.server,)) th.start()
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)
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)
class ReportServer(object): def __init__(self, cacher): 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, 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, ) def serve(self): def run_server(server): server.start() self.server = SocketServer(self.app, auto_start = False) th = Thread(target=run_server, args=(self.server,)) th.start() def stop(self): self.server.stop() def send(self, data): for connection in Client.CONNECTIONS: data['uuid'] = self.reportUUID connection.send(json.dumps(data)) def reload(self): for connection in Client.CONNECTIONS: connection.emit('reload')
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 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)
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)
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()
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
def run(self, ioloop): self.server = SocketServer(self.app, io_loop=ioloop, auto_start=False)
class ReportServer(object): 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) def serve(self): def run_server(server): tornado.ioloop.IOLoop.instance().start() self.server = SocketServer(self.app, auto_start=False) th = Thread(target=run_server, args=(self.server, )) th.start() def stop(self): self.server.stop() def send(self, data): for connection in Client.CONNECTIONS: data['uuid'] = self.reportUUID if self.app_log: self.app_log.debug("Connection: %s. Send Data: %s" \ % (connection, data)) connection.send(json.dumps(data)) def reload(self): for connection in Client.CONNECTIONS: connection.emit('reload') def render_offline(self): loader = template.Loader( os.path.join(os.path.dirname(__file__), "templates")) cached_data = { 'data': self.cacher.get_all_data(), 'uuid': self.reportUUID, } return loader.load('offline.jade').generate( cached_data=json.dumps(cached_data))
'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) if __name__ == "__main__": parse_command_line() app = Application() print "listen tcp 8887" # 要先启动,不然的话得不到客户端链接 app.agent.listen(8887) SocketServer(app) print "http://{}:{}".format("localhost", 8888) IOLoop.current().start()
# 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) STATS = ServerStats() redis = brukva.Client(host='localhost', port=6379, selected_db=0) redis.connect() redis.subscribe('events') redis.listen(broadcast_events) ioloop.IOLoop.instance().start()
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 SocketServer(application)
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)