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 startService(self): factory = WebSocketServerFactory("ws://localhost:%d" % self.port, debug=self.debug) factory.protocol = EchoServerProtocol factory.setProtocolOptions( allowHixie76=True) # needed if Hixie76 is to be supported # 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("echows", "web")) root = File(webdir) # and our WebSocket server under "/ws" root.putChild("ws", resource) # both under one Twisted Web Site site = Site(root) site.protocol = HTTPChannelHixie76Aware # needed if Hixie76 is to be supported self.site = site self.factory = factory self.listener = reactor.listenTCP(self.port, site)
def setUp(): 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 = Resource() # root.putChild(constants.WEB_DYNAMIC_BRANCH, resource) from autobahn.twisted.resource import WebSocketResource, HTTPChannelHixie76Aware from twisted.web.server import Site 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 startup(): if not os.path.exists('data/firmware'): os.makedirs('data/firmware') if not os.path.exists('data/static'): os.makedirs('data/static') if not os.path.exists('data/cert'): os.makedirs('data/cert') # Check the certificate file host = getHost() validateCertHost('data/cert/key.pem', 'data/cert/cert.pem', 'data/static/thumb.txt', host) # Start up the HTTPS server web_port = 443 root_handler = File('./data/static/') firmware_handler = FirmwareHandler('data/firmware/') root_handler.putChild('firmware', firmware_handler) site = Site(root_handler) site.protocol = MyHttpChannel reactor.listenTCP(web_port, site) # Start up the HTTP server root_handler_http = File("./data/static/") config_handler = File("./config.html") root_handler_http.putChild('config.html', config_handler) site_http = Site(root_handler_http) reactor.listenTCP(8080, site_http) reactor.suggestThreadPoolSize(50) printStatus("Startup complete, running main loop...") # Run the main loop, this never returns: reactor.run()
def setUp(): 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") from orm.database_init import init_db, db_session from apps.web import constants init_db() from pdb import set_trace set_trace() from apps.web import main_resource root = main_resource.Root() reactor.listenTCP(8000, server.Site(main_resource.Root())) factory = BroadcastServerFactory("ws://127.0.0.1:8011", debug=debug, debugCodePaths=debug) 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 startService(self): factory = WebSocketServerFactory("ws://localhost:%d" % self.port, debug=self.debug) factory.protocol = EchoServerProtocol factory.setProtocolOptions(allowHixie76=True) # needed if Hixie76 is to be supported # 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("echows", "web")) root = File(webdir) # and our WebSocket server under "/ws" root.putChild("ws", resource) # both under one Twisted Web Site site = Site(root) site.protocol = HTTPChannelHixie76Aware # needed if Hixie76 is to be supported self.site = site self.factory = factory self.listener = reactor.listenTCP(self.port, site)
def start(self): """ start websocket server """ logger.info('start websocket server at %s', self._url) self._factory = MyWebSocketServerFactory( self._url, debug=self._debug ) self._factory.protocol = MyWebSocketServerProtocol self._factory.setProtocolOptions(allowHixie76=True) self._resource = WebSocketResource(self._factory) # we server static files under "/" .. root = File('.') # and our WebSocket server under "/websocket" root.putChild('websocket', self._resource) # both under one Twisted Web Site site = Site(root) site.protocol = HTTPChannelHixie76Aware reactor.listenTCP(self._port, site) self._thread = threading.Thread(target=reactor.run, args=(False,)) self._thread.start()
def run_dev_server(): global sender global ws_handler app.secret_key = "SECRET" app.debug = True ## create a Twisted Web resource for our WebSocket server wsFactory = BroadcastServerFactory(ws_url, debug=True, debugCodePaths=True) wsFactory.protocol = EchoServerProtocol wsFactory.setProtocolOptions(allowHixie76=True) wsResource = WebSocketResource(wsFactory) ## create a Twisted Web WSGI resource for our Flask server wsgiResource = WSGIResource(reactor, reactor.getThreadPool(), app) ## create a root resource serving everything via WSGI/Flask, but ## the path "/ws" served by our WebSocket stuff rootResource = WSGIRootResource(wsgiResource, {'ws': wsResource}) ## create a Twisted Web Site and run everything site = Site(rootResource) site.protocol = HTTPChannelHixie76Aware sender = MessageSender(wsFactory) wsFactory.sender = sender ws_handler = wsFactory reactor.listenTCP(port, site) reactor.run()
def run_twisted_server(ip, port): rootResource = WSGIRootResource(createDjangoEndPoint(),{}) site = Site(rootResource) site.protocol = HTTPChannelHixie76Aware from twisted.python import log as log_twisted log_twisted.startLogging(sys.stdout) reactor.listenTCP(port, site, interface=ip) reactor.run()
def boot(listen_addr='127.0.0.1', port=8080, session_bus=False, sage_www_root=DEFAULT_SAGE_ROOT, auth_realm=None, auth_passwd=None, allow_ga=None, deny_ga=None, no_www=False): assert not ( allow_ga and deny_ga ), 'Must not specify both deny and allow rules for group addresses' global api global factory DBusGMainLoop(set_as_default=True) if session_bus: bus = dbus.SessionBus() else: bus = dbus.SystemBus() obj = bus.get_object(DBUS_SERVICE, DBUS_PATH) api = dbus.Interface(obj, DBUS_INTERFACE) uri = createWsUrl(listen_addr, port) factory = SageProtocolFactory(uri, debug=False, api=api, allow_ga=allow_ga, deny_ga=deny_ga) factory.setProtocolOptions(allowHixie76=True, webStatus=False) factory.protocol = SageProtocol factory.clients = [] resource = WebSocketResource(factory) if no_www: root = resource else: root = File(sage_www_root) root.putChild('saged', resource) if auth_realm != None and auth_passwd != None: portal = Portal(SageRealm(root), [ApachePasswordDB(auth_passwd)]) credentialFactories = [ BasicCredentialFactory(auth_realm), ] root = HTTPAuthSessionWrapper(portal, credentialFactories) site = Site(root) site.protocol = HTTPChannelHixie76Aware reactor.listenTCP(port, site, interface=listen_addr) reactor.run()
def __init__(self, reactor, port): self.reactor = reactor self.app = create_app() self.thread_pool = ThreadPool(maxthreads=config.THREAD_POOL_MAX) self.thread_pool.start() wsgi_resource = WSGIResource(self.reactor, self.thread_pool, self.app) root_resource = RootResource(wsgi_resource) root_resource.putChild("proxy", ProxyResource(self.app)) site = Site(root_resource) site.protocol = HTTPChannelWithClient self.bind = self.reactor.listenTCP(port, site) log.info('Server is listening on %s ...' % port)
def _create_web_factory(self, config, is_secure): options = config.get('options', {}) # create Twisted Web root resource if '/' in config['paths']: root_config = config['paths']['/'] root = self._create_resource(root_config, nested=False) else: root = Resource404(self._templates, b'') # create Twisted Web resources on all non-root paths configured self._add_paths(root, config.get('paths', {})) # create the actual transport factory transport_factory = Site( root, timeout=options.get('client_timeout', None), ) transport_factory.noisy = False # we override this factory so that we can inject # _LessNoisyHTTPChannel to avoid info-level logging on timing # out web clients (which happens all the time). def channel_protocol_factory(): return _GenericHTTPChannelProtocol(_LessNoisyHTTPChannel()) transport_factory.protocol = channel_protocol_factory # Web access logging if not options.get('access_log', False): transport_factory.log = lambda _: None # Traceback rendering transport_factory.displayTracebacks = options.get('display_tracebacks', False) # HSTS if options.get('hsts', False): if is_secure: hsts_max_age = int(options.get('hsts_max_age', 31536000)) transport_factory.requestFactory = createHSTSRequestFactory(transport_factory.requestFactory, hsts_max_age) else: self.log.warn("Warning: HSTS requested, but running on non-TLS - skipping HSTS") return transport_factory
def boot(listen_addr='127.0.0.1', port=8080, session_bus=False, sage_www_root=DEFAULT_SAGE_ROOT, auth_realm=None, auth_passwd=None, allow_ga=None, deny_ga=None, no_www=False): assert not (allow_ga and deny_ga), 'Must not specify both deny and allow rules for group addresses' global api global factory DBusGMainLoop(set_as_default=True) if session_bus: bus = dbus.SessionBus() else: bus = dbus.SystemBus() obj = bus.get_object(DBUS_SERVICE, DBUS_PATH) api = dbus.Interface(obj, DBUS_INTERFACE) uri = createWsUrl(listen_addr, port) factory = SageProtocolFactory(uri, debug=False, api=api, allow_ga=allow_ga, deny_ga=deny_ga) factory.setProtocolOptions(allowHixie76=True, webStatus=False) factory.protocol = SageProtocol factory.clients = [] resource = WebSocketResource(factory) if no_www: root = resource else: root = File(sage_www_root) root.putChild('saged', resource) if auth_realm != None and auth_passwd != None: portal = Portal(SageRealm(root), [ApachePasswordDB(auth_passwd)]) credentialFactories = [BasicCredentialFactory(auth_realm),] root = HTTPAuthSessionWrapper(portal, credentialFactories) site = Site(root) site.protocol = HTTPChannelHixie76Aware reactor.listenTCP(port, site, interface=listen_addr) reactor.run()
def main(): writelog('starting server') if len(sys.argv) > 1 and sys.argv[1] == 'debug': log.startLogging(sys.stdout) debug = True #print 'debuggin' else: debug = False log.startLogging(DailyLogFile.fromFullPath("/var/log/sprinkler.log")) debug = True contextFactory = ssl.DefaultOpenSSLContextFactory( '/home/pi/cron/keys/server.key', '/home/pi/cron/keys/server.crt') ServerFactory = BroadcastServerFactory #ServerFactory = BroadcastPreparedServerFactory factory = ServerFactory("wss://localhost:5000", debug=debug, debugCodePaths=debug) factory2 = ServerFactory("ws://localhost:5001", debug=debug, debugCodePaths=debug) factory.protocol = BroadcastServerProtocol factory.setProtocolOptions(allowHixie76=True) factory2.protocol = BroadcastServerProtocol factory2.setProtocolOptions(allowHixie76=True) listenWS(factory2) listenWS(factory, contextFactory) webdir = File("/home/pi/cron/sprinklerwww/") web = Site(webdir) web.protocol = HTTPChannelHixie76Aware webdir.contentTypes['.crt'] = 'application/x-x509-ca-cert' print 'starting server' webdir.putChild("sChange", sChange()) webdir.putChild("schedule", schedule()) webdir.putChild("manual", manual()) #reactor.listenTCP(8080, web) reactor.listenSSL(8081, web, contextFactory) reactor.run()
def main(): writelog('starting server') if len(sys.argv) > 1 and sys.argv[1] == 'debug': log.startLogging(sys.stdout) debug = True #print 'debuggin' else: debug = False log.startLogging(DailyLogFile.fromFullPath("/var/log/sprinkler.log")) debug = True contextFactory = ssl.DefaultOpenSSLContextFactory('/home/pi/cron/keys/server.key', '/home/pi/cron/keys/server.crt') ServerFactory = BroadcastServerFactory #ServerFactory = BroadcastPreparedServerFactory factory = ServerFactory("wss://localhost:5000", debug = debug, debugCodePaths = debug) factory2 = ServerFactory("ws://localhost:5001", debug = debug, debugCodePaths = debug) factory.protocol = BroadcastServerProtocol factory.setProtocolOptions(allowHixie76 = True) factory2.protocol = BroadcastServerProtocol factory2.setProtocolOptions(allowHixie76 = True) listenWS(factory2) listenWS(factory,contextFactory) webdir = File("/home/pi/cron/sprinklerwww/") web = Site(webdir) web.protocol = HTTPChannelHixie76Aware webdir.contentTypes['.crt'] = 'application/x-x509-ca-cert' print 'starting server' webdir.putChild("sChange",sChange()) webdir.putChild("schedule",schedule()) webdir.putChild("manual",manual()) #reactor.listenTCP(8080, web) reactor.listenSSL(8081,web,contextFactory) reactor.run()
def _site_init(self, debug): # Twisted Web resource for our WAMP factory ws_resource = WebSocketResource(self.factory) # Write hardwire settings to JS file with open(os.path.join(self._hw_dir, 'static', 'js', 'hw-settings.js'), 'w+') as f: f.write('var hw_settings = {port: %d}' % self._port) # Twisted Web resource for static assets hw_static_resource = File(os.path.join(self._hw_dir, 'static')) # Create root resource from either the user's WSGI app, the user's # index.html, or the Hardwire default index.html if self._app: print "Using user-supplied WSGI app..." wsgi_resource = WSGIResource(reactor, reactor.getThreadPool(), self._app) child_resources = {'hw_static': hw_static_resource, \ 'static': static_resource, \ settings.WSURI_SUFFIX: ws_resource} root_resource = WSGIRootResource(wsgi_resource, child_resources) else: user_index_path = os.path.join(self._user_dir, 'index.html') if os.path.isfile(user_index_path): print "Using user-supplied index.html..." index_path = self._user_dir else: print "Using Hardwire default index.html..." index_path = os.path.join(self._hw_dir, 'templates') root_resource = File(index_path) root_resource.putChild("hw_static", hw_static_resource) root_resource.putChild(settings.WSURI_SUFFIX, ws_resource) if debug: log.startLogging(sys.stdout) site = Site(root_resource) site.protocol = HTTPChannelHixie76Aware # needed if Hixie76 is supported reactor.listenTCP(self._port, site)
def makeService(self, options): """ Construct a TCPServer from a factory defined in myproject. """ ws_factory = ReveilleServerFactory("ws://localhost:%d" % options["port"]) ws_factory.setProtocolOptions(allowHixie76=True) ## need to start manually, see https://github.com/tavendo/AutobahnPython/issues/133 ws_factory.startFactory() #listenWS(ws_factory) ## Twisted Web resource for our WAMP factory ws_resource = WebSocketResource(ws_factory) stream_factory = WscpServerFactory("ws://localhost:%d" % options["port"], #'/data/music_archive', '/Users/davidb/src') stream_factory.setProtocolOptions(allowHixie76=True) ## need to start manually, see https://github.com/tavendo/AutobahnPython/issues/133 stream_factory.startFactory() #listenWS(stream_factory) ## Twisted Web resource for our WAMP factory stream_resource = WebSocketResource(stream_factory) ## we server static files under "/" .. root = File(".") ## and our WAMP server under "/reveille" root.putChild("reveille", ws_resource) ## and our WebSocket server under "/stream" root.putChild("stream", stream_resource) ## both under one Twisted Web Site site = Site(root) site.protocol = HTTPChannelHixie76Aware # needed if Hixie76 is to be supported return internet.TCPServer(int(options["port"]), site)
def startup(): if not os.path.exists('data/firmware'): os.makedirs('data/firmware') if not os.path.exists('data/static'): os.makedirs('data/static') if not os.path.exists('data/cert'): os.makedirs('data/cert') # Check the certificate file host = getHost() validateCertHost('data/cert/key.pem', 'data/cert/cert.pem', 'data/static/thumb.txt', host) # Start up the HTTPS server web_port = 443 root_handler = File('./data/static/') firmware_handler = FirmwareHandler('data/firmware/') root_handler.putChild('firmware', firmware_handler) site = Site(root_handler) site.protocol = MyHttpChannel reactor.listenTCP(web_port, site) # Start up the HTTP server root_handler_http = File("./data/static/") #config_handler = File("./config.html") #root_handler_http.putChild('config.html', config_handler) site_http = Site(root_handler_http) reactor.listenTCP(8080, site_http) reactor.suggestThreadPoolSize(50) #printStatus("Startup complete, running main loop...") print "" print "Using another WiFi capable device (NOT this machine) connect to your network, open a browser and go to: http://"+host+":8080 and follow the instructions to update your Oak." print "" print "NOTE: You must use the config app at that address, it is configured specifically for this local update. Status messages will print here during the update. Do not close this window until you have finished updating." # Run the main loop, this never returns: reactor.run()
def __init__(self, reactor, port): self.reactor = reactor self.reactor.addSystemEventTrigger('before', 'shutdown', self.before_shutdown) self.reactor.addSystemEventTrigger('during', 'shutdown', self.during_shutdown) self.reactor.suggestThreadPoolSize(config.REACTOR_THREAD_POOL_MAX) self.app = create_app() self.thread_pool = ThreadPool(maxthreads=config.FLASK_THREAD_POOL_MAX) self.thread_pool.start() wsgi_resource = WSGIResource(self.reactor, self.thread_pool, self.app) root_resource = RootResource(wsgi_resource) root_resource.putChild("proxy", ProxyResource(self.app)) root_resource.putChild("metrics", MetricsResource()) site = Site(root_resource) site.protocol = HTTPChannelWithClient self.bind = self.reactor.listenTCP(port, site) self._wait_for_end_active_sessions = getattr(config, 'WAIT_ACTIVE_SESSIONS', False) log.info('Server is listening on %s ...' % port)
def startService(self): log.msg("Starting %s service ..." % self.SERVICENAME) issecure = self.services["config"]["hub-websocket-tls"] port = self.services["config"]["hub-websocket-port"] acceptqueue = self.services["config"]["ws-accept-queue-size"] if issecure: contextFactory = TlsContextFactory(self.services["config"]["hub-websocket-tlskey-pem"], self.services["config"]["hub-websocket-tlscert-pem"], dhParamFilename = self.services['master'].dhParamFilename) uri = "wss://localhost:%d" % port else: contextFactory = None uri = "ws://localhost:%d" % port self.wsfactory = HubWebSocketFactory(uri, self.dbpool, self.services) #self.wsfactory.trackTimings = True self.enableAppWeb = self.services["config"]["service-enable-appweb"] if self.enableAppWeb: ## FIXME: Site.start/stopFactory should start/stop factories wrapped as Resources self.wsfactory.startFactory() resource = WebSocketResource(self.wsfactory) appwebDir = self.services["master"].webdata root = File(appwebDir) root.putChild(self.services["config"]["ws-websocket-path"], resource) ## CGI ## cgienable = self.services["config"]["appweb-cgi-enable"] cgipath = self.services["config"]["appweb-cgi-path"] cgiprocessor = self.services["config"]["appweb-cgi-processor"] if cgienable and cgipath is not None and cgipath.strip() != "" and cgiprocessor is not None and cgiprocessor.strip() != "": cgipath = cgipath.strip() cgidir = os.path.join(appwebDir, cgipath) cgiprocessor = cgiprocessor.strip() cgiresource = CgiDirectory(cgidir, cgiprocessor) root.putChild(cgipath, cgiresource) log.msg("CGI configured on path '%s' using processor '%s'" % (cgipath, cgiprocessor)) else: log.msg("No CGI configured") factory = Site(root) factory.log = lambda _: None # disable any logging factory.protocol = HTTPChannelHixie76Aware # needed if Hixie76 is to be supported ## REST interface to get config values ## configPath = self.services["config"]["ws-websocket-path"] + "config" addPortConfigResource(self.services["config"], root, configPath) else: factory = self.wsfactory self.factory = factory if issecure: self.listener = reactor.listenSSL(port, factory, contextFactory, backlog = acceptqueue) else: self.listener = reactor.listenTCP(port, factory, backlog = acceptqueue) self.isRunning = True
if __name__ == '__main__': bridge = Bridge() log.startLogging(sys.stdout) # websocket setup wsAddress = 'ws://%s:%d' % (SERVER_IP, SERVER_WS_PORT) factory = BridgedWebSocketServerFactory(wsAddress, False, False, bridge) factory.protocol = WebSocketServer reactor.listenTCP(SERVER_WS_PORT, factory) # http setup webdir = os.path.abspath(SERVER_HTTP_RESOURCES) site = Site(File(webdir)) site.protocol = HTTPChannelHixie76Aware reactor.listenTCP(SERVER_HTTP_PORT, site) # udp setup reactor.listenUDP(SERVER_UDP_PORT, UDPServer(bridge)) # start session reactor.run()
SERVER_WS_PORT = 8000 SERVER_HTTP_PORT = 9000 SERVER_HTTP_RESOURCES = 'web' bridge = Bridge() log.startLogging(sys.stdout) # websocket setup wsAddress = 'wss://%s:%d' % (SERVER_IP, SERVER_WS_PORT) contextFactory = ssl.DefaultOpenSSLContextFactory('/etc/apache2/ssl/localhost.key', '/etc/apache2/ssl/localhost.crt') wsfactory = BridgedWebSocketServerFactory(wsAddress, False, False, bridge) wsfactory.protocol = WebSocketServer reactor.listenSSL(SERVER_WS_PORT, wsfactory, contextFactory) # http setup webdir = os.path.abspath(SERVER_HTTP_RESOURCES) site = Site(File(webdir)) site.protocol = HTTPChannelHixie76Aware reactor.listenTCP(SERVER_HTTP_PORT, site) usbclient = USBClient(bridge) print('About to open serial port {0} [{1} baud] ..'.format(port, baudrate)) try: SerialPort(usbclient, port, reactor, baudrate=baudrate) except Exception as e: print('Could not open serial port: {0}'.format(e)) reactor.run()
SERVER_WS_PORT = 8000 SERVER_HTTP_PORT = 9000 SERVER_HTTP_RESOURCES = 'web' bridge = Bridge() log.startLogging(sys.stdout) # websocket setup wsAddress = 'wss://%s:%d' % (SERVER_IP, SERVER_WS_PORT) contextFactory = ssl.DefaultOpenSSLContextFactory( '/etc/apache2/ssl/localhost.key', '/etc/apache2/ssl/localhost.crt') wsfactory = BridgedWebSocketServerFactory(wsAddress, False, False, bridge) wsfactory.protocol = WebSocketServer reactor.listenSSL(SERVER_WS_PORT, wsfactory, contextFactory) # http setup webdir = os.path.abspath(SERVER_HTTP_RESOURCES) site = Site(File(webdir)) site.protocol = autobahn.twisted.resource.HTTPChannelHixie76Aware reactor.listenTCP(SERVER_HTTP_PORT, site) usbclient = USBClient(bridge) print('About to open serial port {0} [{1} baud] ..'.format(port, baudrate)) try: SerialPort(usbclient, port, reactor, baudrate=baudrate) except Exception as e: print('Could not open serial port: {0}'.format(e)) reactor.run()
def websocket_func(logger, host, port): cons = list() # noinspection PyUnusedLocal def sigint_handler(signum, frame): reactor.stop() signal.signal(signal.SIGINT, sigint_handler) def send_to_all(msg, except_connection=None): if except_connection: logger.debug("Sending to all except %d message: %s", id(except_connection), msg) else: logger.debug("Sending to all: %s", msg) json_msg = json.dumps(msg) for con in cons: if con == except_connection: continue logger.debug("Sending to %d message: %s", id(con), msg) con.sendMessage(json_msg, False) class EchoServerProtocol(WebSocketServerProtocol): def __init__(self): pass def send_error(self, error_message): logger.error(error_message) self.send_to_self({"type": "error", "response": error_message}) def send_to_self(self, msg): logger.debug("Sending to self: %s", msg) json_msg = json.dumps(msg) self.sendMessage(json_msg, False) def send_to_others(self, msg): send_to_all(msg, self) def onMessage(self, msg, binary): if binary: return try: data = json.loads(msg) data_type = str(data["type"]) if "ping" == data_type: self.on_message_ping(data) elif "register" == data_type: self.on_message_register(data) elif "data" == data_type: self.on_message_data(data) else: self.send_error("Received unknown message type: %s" % data_type) except Exception as e: self.send_error("Error: %s, in message: %s" % (str(e), msg)) def on_message_data(self, data): self.send_to_self({ "type": "data", "id": data["id"], "message": base64.b64encode(data["message"]) }) self.send_to_others({ "type": "chat", "from": str(id(self)), "message": data["message"] }) def on_message_register(self, data): auth_token = data["auth_token"] if auth_token in VALID_AUTH_TOKENS: cons.append(self) self.send_to_self({"type": "registered", "response": "you are cool"}) else: self.send_error("Wrong auth token") def on_message_ping(self, data): self.send_to_self({"type": "pong", "message": data["message"]}) def onClose(self, was_clean, code, reason): logger.debug("Disconnected: %s" % id(self)) if self in cons: cons.remove(self) def onOpen(self): logger.debug("Connected: %s" % id(self)) url = "ws://%s:%d" % (host, port) factory = WebSocketServerFactory(url) factory.protocol = EchoServerProtocol factory.setProtocolOptions(allowHixie76=True) resource = WebSocketResource(factory) root = Resource() root.putChild("ws", resource) site = Site(root) site.protocol = HTTPChannelHixie76Aware reactor.listenTCP(port, site) logger.info("listening on %s/ws" % url) reactor.run()
## HSTS ## if options.get("hsts", False): if "tls" in config["endpoint"]: hsts_max_age = int(options.get("hsts_max_age", 31536000)) transport_factory.requestFactory = createHSTSRequestFactory( transport_factory.requestFactory, hsts_max_age ) else: log.msg("Warning: HSTS requested, but running on non-TLS - skipping HSTS") ## enable Hixie-76 on Twisted Web ## if options.get("hixie76_aware", False): transport_factory.protocol = HTTPChannelHixie76Aware # needed if Hixie76 is to be supported else: raise Exception("logic error") ## create transport endpoint / listening port from transport factory ## if True: from twisted.internet.endpoints import TCP4ServerEndpoint, SSL4ServerEndpoint, UNIXServerEndpoint from twisted.internet.endpoints import serverFromString from crossbar.twisted.tlsctx import TlsServerContextFactory # server = serverFromString(reactor, "ssl:8080:privateKey=.crossbar/server.key:certKey=.crossbar/server.crt") try:
## create a Twisted Web resource for our WebSocket server ## wsFactory = WebSocketServerFactory("ws://localhost:8080", debug = debug, debugCodePaths = debug) wsFactory.protocol = EchoServerProtocol wsFactory.setProtocolOptions(allowHixie76 = True) # needed if Hixie76 is to be supported wsResource = WebSocketResource(wsFactory) ## ## create a Twisted Web WSGI resource for our Flask server ## wsgiResource = WSGIResource(reactor, reactor.getThreadPool(), app) ## ## create a root resource serving everything via WSGI/Flask, but ## the path "/ws" served by our WebSocket stuff ## rootResource = WSGIRootResource(wsgiResource, {'ws': wsResource}) ## ## create a Twisted Web Site and run everything ## site = Site(rootResource) site.protocol = HTTPChannelHixie76Aware # needed if Hixie76 is to be supported reactor.listenTCP(8080, site) reactor.run()
class MyProtocol(HTTPChannel): _connection_lost = defer.succeed(None) def notifyConnectionLost(self): return self._connection_lost def connectionMade(self): HTTPChannel.connectionMade(self) self._connection_lost = defer.Deferred() def connectionLost(self, reason): HTTPChannel.connectionLost(self, reason) self._connection_lost.callback(None) slow_resource = SlowResource() site = Site(slow_resource) site.protocol = MyProtocol application = service.Application("MyApp") server = internet.TCPServer(8080, site) server.setServiceParent(application) @defer.inlineCallbacks def graceful_shutdown(): yield server.stopService() yield slow_resource.notify_no_more_waiting() reactor.addSystemEventTrigger('before', 'shutdown', graceful_shutdown)
r'''Switch to a new protocol as soon as possible.''' if self.__buffer: data = self.__buffer + data self.__buffer = data print "Received", repr(data) if len(data) >= 4: if "\0" in data: # Binary data; use DCSP self.switchProtocol(DaideProtocol, None) self.transport.setTcpKeepAlive(True) else: # Probably text; switch to HTTP self.switchProtocol(HTTPChannel, self.site.timeOut) def read_RM(self, data): self.send_error(self.proto.ClientRMError) def handle_message(self, msg): print msg class Nothing(Resource): def getChild(self, name, request): return NoResource() root = Nothing() factory = Site(root) factory.protocol = DaideServerProtocol reactor.listenTCP(8880, factory) reactor.run()
## wsFactory = WebSocketServerFactory("ws://127.0.0.1:8080", debug=debug, debugCodePaths=debug) wsFactory.protocol = EchoServerProtocol wsFactory.setProtocolOptions( allowHixie76=True) # needed if Hixie76 is to be supported wsResource = WebSocketResource(wsFactory) ## # create a Twisted Web WSGI resource for our Flask server ## wsgiResource = WSGIResource(reactor, reactor.getThreadPool(), app) ## # create a root resource serving everything via WSGI/Flask, but # the path "/ws" served by our WebSocket stuff ## rootResource = WSGIRootResource(wsgiResource, {'ws': wsResource}) ## # create a Twisted Web Site and run everything ## site = Site(rootResource) site.protocol = HTTPChannelHixie76Aware # needed if Hixie76 is to be supported reactor.listenTCP(8080, site) reactor.run()
try: data = json.loads(payload.decode('utf8')) except Exception as e: print("Error receiving input from socket") return if data and 'data' in data: input_buffer.append(data['data']) # echo back message verbatim self.sendMessage(payload, isBinary) def onClose(self, wasClean, code, reason): print("WebSocket connection closed: {0}".format(reason)) global_sockets.remove(self) factory = WebSocketServerFactory("ws://localhost:8081", debug = True) factory.protocol = MyServerProtocol reactor.listenTCP(8081, factory) def openBrowserConfig(): webbrowser.open('http://127.0.0.1:8080') reactor.callLater(1, openBrowserConfig); reactor.run() sys.exit()