def __init__(self, db): self.db = db self.clients = set([]) factory = RepublishServerFactory("ws://example.com:8079/wsrepublish", debug=False, wsresource=self) WebSocketResource.__init__(self, factory)
def getChild(self, name, request): protoType = request.getHeader('upgrade') if not protoType: if name in self.WSmap: if self.webAuthenticated: return File("/tmp/" + name) else: if self.checkAuth(name, request): return File("/tmp/" + name) else: return ErrorPage() else: return NoResource() elif protoType.lower() == 'websocket': if len(request.postpath) == 1: if (request.postpath[0] == 'control') and (name in self.WScontrolmap): return self.WScontrolmap[name][0] elif request.postpath[0] == 'control': controlFactory = PSFactory() controlFactory.protocol = CommandChannel controlFactory.setProtocolOptions(maxConnections=2) controlFactory.startFactory() self.WScontrolmap[name].append( WebSocketResource(controlFactory)) return self.WScontrolmap[name][0] elif name in self.WSmap: return self.WSmap[name][0] else: factory = PSFactory() factory.protocol = PSProto factory.setProtocolOptions(maxConnections=2) factory.startFactory() self.WSmap[name].append(WebSocketResource(factory)) return self.WSmap[name][0]
def setUp(self): market_factory = WebSocketServerFactory( 'ws://localhost:8080/market_stream') user_factory = WebSocketServerFactory( 'ws://localhost:8080/user_stream') market_factory.protocol = MarketStreamServerProtocol user_factory.protocol = UserStreamServerProtocol market_factory.startFactory() user_factory.startFactory() root = Data('', 'text/plain') root.putChild(b'market_stream', WebSocketResource(market_factory)) root.putChild(b'user_stream', WebSocketResource(user_factory)) site = Site(root) reactor.listenTCP(8080, site) def run_server(): reactor.run(installSignalHandlers=False) Thread(target=run_server).start() def run_client(): from examples import simple_trading self.client_process = Process(target=run_client) self.client_process.start()
def __init__(self, spec_manager, factory): self.spec_manager = spec_manager settings = spec_manager.settings self.settings = spec_manager.settings FerryServerProtocol.spec_manager = spec_manager FerryServerProtocol.settings = settings FerryServerProtocol.assets = factory.assets WebSocketResource.__init__(self, factory)
def getChild(self, name, request): if request.method == "GET": # Let's assume that all file are either empty (-> index.html) or have a period in them. if len(name) == 0 or "." in name: return self.file_resource.getChild(name, request) else: print 'making db', name dbdir = os.path.join(self.dbrootdir, name) subdir_resources = {} dbfactory = CommandDatabase(dbdir, subdir_resources) dbfactory.protocol = minidb.DBProtocol dbws_resource = WebSocketResource(dbfactory) subdir_resources['db'] = dbfactory factory = AudioConferenceFactory(subdir_resources, dbdir, dbfactory) factory.protocol = AudioConferenceProtocol ws_resource = WebSocketResource(factory) subdir_resources['factory'] = factory attachdir = os.path.join(dbdir, "_attachments") attach = TranscodingAttachFactory(factory, dbfactory, attachdir=attachdir) attach.protocol = attachments.AttachProtocol subdir_resources['attach'] = attach attachhttp = File(attachdir) attws_resource = WebSocketResource(attach) zipper = DBZipper(dbfactory) root = File(self.webdir) dbhttp = File(dbdir) root.putChild('_ws', ws_resource) root.putChild('_db', dbws_resource) root.putChild('_attach', attws_resource) root.putChild('db', dbhttp) root.putChild('attachments', attachhttp) root.putChild('download.zip', zipper) self.putChild(name, root) return root return Resource.getChild(self, name, request)
def trade_server(): root = File("./htdocs") # for _symbol in MARKETS.keys(): root.putChild(str.encode(_symbol), resource) factory = EchoServerFactory() factory.protocol = EchoServerProtocol factory.startFactory( ) # when wrapped as a Twisted Web resource, start the underlying factory manually resource = WebSocketResource(factory) root.putChild(b"wss", resource) root.putChild(b"symbols", SymbolPage()) # 用于向页面传递交易对接口 root.putChild(b"signin", SignInPage()) # 登录页面 root.putChild(b"logout", SignOutPage()) # 登出页面 root.putChild(b"logchk", LogCheckPage()) # 登陆状态检测接口 root.putChild(b"setlost", SetLostPage()) # 设置全局变量是否自动止损 root.putChild(b"trade", TradePage()) # 交易接口 root.putChild(b"cancel", CancelPage()) # 取消所有订单 root.putChild(b"contract", GetCoinsPage()) # 获取最新价格接口 root.putChild(b"topdown", TopDownPage()) # 获取和设置当前品种的压力和支撑价格 # use TLS privkey = open('cert/server.key', 'rt').read() certif = open('cert/fullchain.cer', 'rt').read() privkeypyssl = crypto.load_privatekey(crypto.FILETYPE_PEM, privkey) certifpyssl = crypto.load_certificate(crypto.FILETYPE_PEM, certif) contextFactory = ssl.CertificateOptions(privateKey=privkeypyssl, certificate=certifpyssl) site = Site(root) site.sessionFactory = longTimeoutSession reactor.listenSSL(SRV_PORT, site, contextFactory) # reactor.listenTCP(SRV_PORT, site) reactor.run()
def bind(self): """ Start listening on the port specified """ factory = WebSocketServerFactory(debug=False) factory.noisy = False factory.server = self factory.protocol = MdcloudWebsocketServerProtocol web_resource = File(resource_filename(__name__, 'static/build/client')) rootResource = WSGIRootResource(web_resource, {'ws': WebSocketResource(factory)}) if not self.no_ssl and self.settings and self.settings.ssl.enabled: print '*' * 60 print 'Running in secure mode' print 'Ssl key: %s' % self.settings.ssl.key print 'Ssl certificate: %s' % self.settings.ssl.cert print '*' * 60 listen_ssl(self.port, Site(rootResource), interface=self.settings.websocket_ip) else: print '*' * 60 print 'Running on 0.0.0.0 without SSL' print '*' * 60 reactor.listenTCP(self.port, Site(rootResource), interface='0.0.0.0')
def main(): logging.basicConfig(level=logging.INFO, format=config.logger_format) parser = argparse.ArgumentParser(description="ROSE Server") parser.add_argument("--track_definition", "-t", dest="track_definition", default="random", choices=["random", "same"], help="Definition of driver tracks: random or same." "If not specified, random will be used.") args = parser.parse_args() """ If the argument is 'same', the track will generate the obstacles in the same place for both drivers. Otherwise, the obstacles will be genrated in random locations for each driver. """ if args.track_definition == "same": config.is_track_random = False else: config.is_track_random = True log.info('starting server') g = game.Game() h = net.Hub(g) reactor.listenTCP(config.game_port, net.PlayerFactory(h)) root = static.File(config.web_root) wsuri = u"ws://%s:%s" % (socket.gethostname(), config.web_port) watcher = net.WatcherFactory(wsuri, h) root.putChild(b"ws", WebSocketResource(watcher)) root.putChild(b'res', static.File(config.res_root)) root.putChild(b'admin', net.WebAdmin(g)) root.putChild(b'rpc2', net.CliAdmin(g)) site = server.Site(root) reactor.listenTCP(config.web_port, site) reactor.run()
def run_server(): log.startLogging(sys.stdout) env = Env() env.read_env() location = "ws://127.0.0.1:8080" factory = WebSocketServerFactory(location) factory.protocol = ServerProtocol factory.setProtocolOptions(autoPingInterval=5, autoPingTimeout=60) resource = WebSocketResource(factory) root = File("./public/") root.putChild(b"ws", resource) site = Site(root) def handle_requests(): for request in factory.protocol.requests: f = request[0] arguments = request[1] f(*arguments) factory.protocol.requests = [] handler.send_messages() handle = task.LoopingCall(handle_requests) handle.start(0.2) reactor.listenTCP(8080, site) reactor.run()
def create(transport, path, config): ws_rproxy_factory = WebSocketReverseProxyServerFactory( transport._worker._reactor, config) ws_rproxy_factory.startFactory() resource = WebSocketResource(ws_rproxy_factory) return RouterWebServiceWebSocketReverseProxy(transport, path, config, resource)
def start_service(token, root, project): def clean(tmp_path): print('Cleaning up {}'.format(tmp_path), file=sys.stderr) shutil.rmtree(tmp_path, True) temp_path = project['tempdir'] if temp_path is None: temp_path = tempfile.mkdtemp() atexit.register(clean, temp_path) output_path = os.path.join(temp_path, 'output') runner = Runner( project['python'], project['pelicanconf'], { 'OUTPUT_PATH': output_path, 'SITEURL': 'site', 'RELATIVE_URLS': True, }, ) factory = WebSocketServerFactory() factory.token = token factory.runner = runner factory.project = project factory.protocol = PelicideService root.putChild('ws', WebSocketResource(factory)) root.putChild('site', NoCacheFile(output_path)) return runner.start().addCallback( lambda _: runner.command('build')).addCallback(lambda _: None)
def startService(self): factory = WebSocketServerFactory(u"ws://127.0.0.1:%d" % self.port, debug=self.debug) factory.protocol = DispatcherProtocol factory.protocol.dispatcher = CommandDispatcher(self._core) # FIXME: Site.start/stopFactory should start/stop factories wrapped as # Resources factory.startFactory() resource = WebSocketResource(factory) # we server static files under "/" .. webdir = os.path.abspath( pkg_resources.resource_filename('leap.bitmask.core', 'web')) root = File(webdir) # and our WebSocket server under "/ws" root.putChild(u'bitmask', resource) # both under one Twisted Web Site site = Site(root) self.site = site self.factory = factory self.listener = reactor.listenTCP(self.port, site)
def server_runner(): if len(sys.argv) > 1 and sys.argv[1] == 'debug': log.startLogging(sys.stdout) debug = True else: debug = False try: import autobahn import twisted except ImportError: sys.exit("Install all dependencies") root = main_page_resource.Root() # root.putChild(constants.WEB_DYNAMIC_BRANCH, resource) reactor.listenTCP(8000, server.Site(root)) factory = BroadcastServerFactory("ws://127.0.0.1:8888", debug=debug, debugCodePaths=debug) #если используется proxy #factory.proxy={'host': '192.168.200.105', 'port': '8088'} factory.protocol = BroadcastServerProtocol factory.setProtocolOptions(allowHixie76=True) ws_resource = WebSocketResource(factory) root.putChild("ws", ws_resource) site = Site(root) site.protocol = HTTPChannelHixie76Aware listenWS(factory) reactor.run()
def CallEndpoint(method, debug=False): "why the debug param? because " f = WebSocketServerFactory(debug=debug, debugCodePaths=debug) f.setSessionParameters(externalPort=8080) #bug in autobahn f.protocol = lambda: RPCProtocol(method) return WebSocketResource(f)
def create_server(app, port): ## # create a Twisted Web resource for our WebSocket server ## ws_factory = WebSocketServerFactory(u"ws://127.0.0.1:5000", debug=app.debug, debugCodePaths=app.debug) ws_factory.protocol = NotificationService ws_resource = WebSocketResource(ws_factory) ## # create a Twisted Web WSGI resource for our Flask server ## wsgi_resource = WSGIResource(reactor, reactor.getThreadPool(), app) ## # create a root resource serving everything via WSGI/Flask, but # the path "/ws" served by our WebSocket stuff ## root_resource = WSGIRootResource(wsgi_resource, {'notification-service': ws_resource}) ## # create a Twisted Web Site and run everything ## site = Site(root_resource) reactor.listenTCP(port, site) reactor.run()
def getChild(self, name, request): if name in self.WSmap: return self.WSmap[name] else: factory = PSFactory() factory.protocol = PSProto factory.startFactory() self.WSmap[name] = WebSocketResource(factory) return self.WSmap[name]
def change_stream(self, request, change_id): change = self.update_manager.find_change(change_id) if change is not None: factory = ChangeStreamFactory(change) factory.setProtocolOptions(autoPingInterval=10, autoPingTimeout=5) return WebSocketResource(factory) else: request.setResponseCode(404) return "{}"
def runatomix(): log.startLogging(stdout) factory = WebSocketServerFactory(u"ws://127.0.0.1:8080") factory.protocol = WebServerProtocol resource = WebSocketResource(factory) root = File(".") root.putChild(u"ws", resource) site = Site(root) reactor.listenTCP(8080, site) reactor.run()
def make_web_server(server, log_requests, websocket_protocol_options=()): root = Root() wsrf = WebSocketServerFactory(None, server) wsrf.setProtocolOptions(**dict(websocket_protocol_options)) root.putChild(b"v1", WebSocketResource(wsrf)) site = PrivacyEnhancedSite(root) site.logRequests = log_requests return site
def create(transport, path, config): websocket_factory = WampWebSocketServerFactory( transport._worker._router_session_factory, transport.cbdir, config, transport.templates) # FIXME: Site.start/stopFactory should start/stop factories wrapped as Resources websocket_factory.startFactory() resource = WebSocketResource(websocket_factory) return RouterWebServiceWebSocket(transport, path, config, resource)
def create(transport, path, config, controller): # this is the crossbar-specific wamp-websocket-server # from crossbar.router.protocol import WampWebSocketServerFactory from autobahn.twisted.websocket import WampWebSocketServerFactory websocket_factory = WampWebSocketServerFactory(FrontendProxySession) websocket_factory.protocol = Frontend websocket_factory._controller = controller resource = WebSocketResource(websocket_factory) return ProxyWebSocketService(transport, path, config, resource)
def __init__(self): self.session = None self._sessions = set() self._factory = WebSocketServerFactory(url=None, debug=False, debugCodePaths=False) self._factory.setProtocolOptions(autoPingInterval=15, autoPingTimeout=3) self._factory.protocol = DreamboxServerProtocol self.root = WebSocketResource(self._factory) DreamboxServerProtocol.server = None
def __init__(self, chat, port): self.factory = WebSocketServerFactory(f'ws://127.0.0.1:{port}/ws') self.factory.protocol = TwistedWsProtocol self.factory.protocol.chat = chat ws_resource = WebSocketResource(self.factory) root = Resource() root.putChild(b"ws", ws_resource) root.putChild(b"static", static.File(STATIC_DIR)) root.putChild(b"", static.File(os.path.join(TEMPLATES_DIR, 'index.html'))) self.site = Site(root)
def __init__(self, rendezvous_web_port, transit_port, advertise_version, db_url=":memory:", blur_usage=None): service.MultiService.__init__(self) self._blur_usage = blur_usage db = get_db(db_url) welcome = { "current_version": __version__, # adding .motd will cause all clients to display the message, # then keep running normally #"motd": "Welcome to the public relay.\nPlease enjoy this service.", # # adding .error will cause all clients to fail, with this message #"error": "This server has been disabled, see URL for details.", } if advertise_version: welcome["current_version"] = advertise_version rendezvous = Rendezvous(db, welcome, blur_usage) rendezvous.setServiceParent(self) # for the pruning timer root = Root() wr = WebRendezvous(rendezvous) root.putChild(b"wormhole-relay", wr) wsrf = WebSocketRendezvousFactory(None, rendezvous) wr.putChild(b"ws", WebSocketResource(wsrf)) site = PrivacyEnhancedSite(root) if blur_usage: site.logRequests = False r = endpoints.serverFromString(reactor, rendezvous_web_port) rendezvous_web_service = ServerEndpointService(r, site) rendezvous_web_service.setServiceParent(self) if transit_port: transit = Transit(db, blur_usage) transit.setServiceParent(self) # for the timer t = endpoints.serverFromString(reactor, transit_port) transit_service = ServerEndpointService(t, transit) transit_service.setServiceParent(self) # make some things accessible for tests self._db = db self._rendezvous = rendezvous self._root = root self._rendezvous_web = wr self._rendezvous_web_service = rendezvous_web_service self._rendezvous_websocket = wsrf if transit_port: self._transit = transit self._transit_service = transit_service
def main(): log.startLogging(sys.stdout) root = File("web") factory = ChatFactory(u"ws://127.0.0.1:8080") factory.protocol = ChatServerProtocol resource = WebSocketResource(factory) root.putChild(u"ws", resource) site = Site(root) reactor.listenTCP(8080, site) reactor.run()
def get_websocket_site(self): ''' Returns websocket site ''' try: root = Resource() #use Resource() else file system gets visible resource = WebSocketResource(self.websocket) root.putChild(b"", resource) site = Site(root) # just return websocket site except Exception as e: print(e) return site
def __init__(self, config, controller): super(WebApp, self).__init__() self.config = config self.controller = controller self.children = {} #----------------------------------------------------------------------- # Register web modules #----------------------------------------------------------------------- web_modules = config.get_options('web-modules') for mod_name, mod_class_name in web_modules: mod_class = get_object(mod_class_name) self.putChild(mod_name.encode('utf-8'), mod_class(self)) #----------------------------------------------------------------------- # Set up the websocket #----------------------------------------------------------------------- ws_factory = WSFactory(controller=self.controller) ws_factory.protocol = WSProtocol ws_resource = WebSocketResource(ws_factory) self.putChild(b'ws', ws_resource) #----------------------------------------------------------------------- # Register UI modules #----------------------------------------------------------------------- assets = None try: assets = get_data(__package__, 'ui/asset-manifest.json') assets = assets.decode('utf-8') except FileNotFoundError: self.index = self if assets is not None: self.index = UIResource('ui/index.html') self.putChild(b'', self.index) children = [ '/favicon.png', '/manifest.json', '/scrapy-do-logo.png' ] for child in children: self.register_child(child, UIResource('ui' + child)) assets = json.loads(assets) for _, asset in assets.items(): if asset.startswith('/'): asset = asset[1:] self.register_child('/' + asset, UIResource('ui/' + asset))
def main(): g = game.Game() h = net.Hub(g) reactor.listenTCP(config.game_port, net.PlayerFactory(h)) root = static.File(config.web_root) wsuri = u"ws://%s:%s" % (socket.gethostname(), config.web_port) watcher = net.WatcherFactory(wsuri, h) root.putChild("ws", WebSocketResource(watcher)) root.putChild('res', static.File(config.res_root)) root.putChild('admin', net.WebAdmin(g)) root.putChild('rpc2', net.CliAdmin(g)) site = server.Site(root) reactor.listenTCP(config.web_port, site) reactor.run()
def start_listening(self): resource = WebSocketResource(self) # serve files from ./client root = File(STATIC_FILES) root.putChild(b"ws", resource) site = Site(root) self.port = listen_tcp(self.portrange, self.host, site) h = self.port.getHost() self.logger.debug("Inspectr available on %(host)s:%(port)d", {'host': h.host, 'port': h.port}, extra={'crawler': self.crawler}) if self.crawler.settings.get('INSPECTR_AUTOSTART', None): webbrowser.open('http://{}:{}'.format(h.host, h.port))
def startService(self): root = static.File(os.path.join(os.path.dirname(__file__), 'public')) factory = ServerFactory() factory.status = False factory.led = GPIOHandler(22) factory.protocol = ServerProtocol # factory.setProtocolOptions(maxConnections=2) factory.startFactory() resource = WebSocketResource(factory) root.putChild('socket', resource) site = server.Site(root) self.server = reactor.listenTCP(self.port, site)
def __init__(self, url): #TODO: Autobahn 0.8.6 fixes the oversight that forced url to be included like this. WebSocketResource.__init__(self, PubSubBroker(url, debug = False, debugCodePaths = False))
def __init__(self, wrappedFactory): wsFactory = protocol.WebSocketSessionFactory(wrappedFactory) WebSocketResource.__init__(self, wsFactory)
def __init__(self, factory): FerryServerProtocol.assets = factory.assets WebSocketResource.__init__(self, factory)
def __init__(self, master): WebSocketResource.__init__(self, WsProtocolFactory(master))
def __init__(self, url): WebSocketResource.__init__(self, PubSubBroker(url, debug=False, debugCodePaths=False))
def getChild(self, name, request): _cors(request) return WebSocketResource.getChild(self, name, request)
def render(self, request): request.requestHeaders.setRawHeaders('X-Auth-Info', [json.dumps(request.auth_info)]) return WebSocketResource.render(self, request)