当前位置: 首页>>代码示例>>Python>>正文


Python Site.protocol方法代码示例

本文整理汇总了Python中twisted.web.server.Site.protocol方法的典型用法代码示例。如果您正苦于以下问题:Python Site.protocol方法的具体用法?Python Site.protocol怎么用?Python Site.protocol使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在twisted.web.server.Site的用法示例。


在下文中一共展示了Site.protocol方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: startService

# 需要导入模块: from twisted.web.server import Site [as 别名]
# 或者: from twisted.web.server.Site import protocol [as 别名]
    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)
开发者ID:Avnerus,项目名称:AutobahnPython,代码行数:29,代码来源:echoservice.py

示例2: run_dev_server

# 需要导入模块: from twisted.web.server import Site [as 别名]
# 或者: from twisted.web.server.Site import protocol [as 别名]
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()
开发者ID:Mononofu,项目名称:ZeroChat,代码行数:34,代码来源:main.py

示例3: start

# 需要导入模块: from twisted.web.server import Site [as 别名]
# 或者: from twisted.web.server.Site import protocol [as 别名]
    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()
开发者ID:chikuta,项目名称:autobahn_websocketserver_sample,代码行数:27,代码来源:websocket_server_sample.py

示例4: startup

# 需要导入模块: from twisted.web.server import Site [as 别名]
# 或者: from twisted.web.server.Site import protocol [as 别名]
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()
开发者ID:jldeon,项目名称:OakSoftAP,代码行数:35,代码来源:oakupsrv.py

示例5: setUp

# 需要导入模块: from twisted.web.server import Site [as 别名]
# 或者: from twisted.web.server.Site import protocol [as 别名]
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()
开发者ID:yavalvas,项目名称:yav_com,代码行数:29,代码来源:canvas_server.py

示例6: setUp

# 需要导入模块: from twisted.web.server import Site [as 别名]
# 或者: from twisted.web.server.Site import protocol [as 别名]
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()
开发者ID:yavalvas,项目名称:chess_autobahn,代码行数:30,代码来源:chess_server.py

示例7: run_twisted_server

# 需要导入模块: from twisted.web.server import Site [as 别名]
# 或者: from twisted.web.server.Site import protocol [as 别名]
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()
开发者ID:lodatol,项目名称:django-on-oshift,代码行数:10,代码来源:app.py

示例8: boot

# 需要导入模块: from twisted.web.server import Site [as 别名]
# 或者: from twisted.web.server.Site import protocol [as 别名]
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()
开发者ID:JohnTocher,项目名称:cbus,代码行数:42,代码来源:saged.py

示例9: main

# 需要导入模块: from twisted.web.server import Site [as 别名]
# 或者: from twisted.web.server.Site import protocol [as 别名]
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()
开发者ID:SimplyAutomationized,项目名称:raspberrypi,代码行数:41,代码来源:sprinklerweb.py

示例10: _site_init

# 需要导入模块: from twisted.web.server import Site [as 别名]
# 或者: from twisted.web.server.Site import protocol [as 别名]
    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)
开发者ID:jcrabtr,项目名称:Hardwire,代码行数:41,代码来源:server.py

示例11: makeService

# 需要导入模块: from twisted.web.server import Site [as 别名]
# 或者: from twisted.web.server.Site import protocol [as 别名]
    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)
开发者ID:davidblewett,项目名称:gunny,代码行数:40,代码来源:gunnyd.py

示例12: startup

# 需要导入模块: from twisted.web.server import Site [as 别名]
# 或者: from twisted.web.server.Site import protocol [as 别名]
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()
开发者ID:digistump,项目名称:OakUpdateTool,代码行数:38,代码来源:oakupsrv.py

示例13: WebSocketServerFactory

# 需要导入模块: from twisted.web.server import Site [as 别名]
# 或者: from twisted.web.server.Site import protocol [as 别名]
   ## 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()
开发者ID:BanzaiMan,项目名称:AutobahnPython,代码行数:32,代码来源:server.py

示例14: websocket_func

# 需要导入模块: from twisted.web.server import Site [as 别名]
# 或者: from twisted.web.server.Site import protocol [as 别名]
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

#.........这里部分代码省略.........
开发者ID:Librari,项目名称:JavaWebsocketClient,代码行数:103,代码来源:websocket.py

示例15: startService

# 需要导入模块: from twisted.web.server import Site [as 别名]
# 或者: from twisted.web.server.Site import protocol [as 别名]
   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
开发者ID:jamjr,项目名称:crossbar,代码行数:67,代码来源:hubwebsocket.py


注:本文中的twisted.web.server.Site.protocol方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。