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


Python RouterSessionFactory.add方法代码示例

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


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

示例1: __init__

# 需要导入模块: from autobahn.twisted.wamp import RouterSessionFactory [as 别名]
# 或者: from autobahn.twisted.wamp.RouterSessionFactory import add [as 别名]
class WampServer:

    def __init__(self, debug = '0'):

        self.debug = debug

        log.startLogging(sys.stdout)

        ## we use an Autobahn utility to install the "best" available Twisted reactor
        ##
        from autobahn.twisted.choosereactor import install_reactor
        self.reactor = install_reactor()
        print("Running on reactor {}".format(self.reactor))


        ## create a WAMP router factory
        ##
        from autobahn.twisted.wamp import RouterFactory
        self.router_factory = RouterFactory()


        ## create a WAMP router session factory
        ##
        from autobahn.twisted.wamp import RouterSessionFactory
        self.session_factory = RouterSessionFactory(self.router_factory)


        ## Add embedded WAMP application sessions to the router
        ##
        from core.rpc import MyBackendComponent
        component_config = types.ComponentConfig(realm = "realm1")
        component_session = MyBackendComponent(component_config)
        self.session_factory.add(component_session)

        ## create a WAMP-over-WebSocket transport server factory
        ##
        from autobahn.twisted.websocket import WampWebSocketServerFactory
        self.transport_factory = WampWebSocketServerFactory(self.session_factory, debug = self.debug)
        self.transport_factory.setProtocolOptions(failByDrop = False)


    def run(self, config):
        ## start the server from an endpoint
        ##
        enpoint = 'tcp:' + config.PORT
        print enpoint
        self.server = serverFromString(self.reactor, enpoint)
        self.server.listen(self.transport_factory)

        ## now enter the Twisted reactor loop
        ##
        self.reactor.run()
开发者ID:zjgkkn,项目名称:wsocketdash,代码行数:54,代码来源:wamp.py

示例2: getattr

# 需要导入模块: from autobahn.twisted.wamp import RouterSessionFactory [as 别名]
# 或者: from autobahn.twisted.wamp.RouterSessionFactory import add [as 别名]
   ## if asked to start an embedded application component ..
   ##
   if args.component:
      ## dynamically load the application component ..
      ##
      import importlib
      c = args.component.split('.')
      mod, klass = '.'.join(c[:-1]), c[-1]
      app = importlib.import_module(mod)
      SessionKlass = getattr(app, klass)

      ## .. and create and add an WAMP application session to
      ## run next to the router
      ##
      session_factory.add(SessionKlass())


   ## create a WAMP-over-WebSocket transport server factory
   ##
   from autobahn.twisted.websocket import WampWebSocketServerFactory
   transport_factory = WampWebSocketServerFactory(session_factory, args.wsurl, debug = args.debug)
   transport_factory.setProtocolOptions(failByDrop = False)


   ## start the WebSocket server from an endpoint
   ##
   server = serverFromString(reactor, args.websocket)
   server.listen(transport_factory)

开发者ID:alisaifee,项目名称:AutobahnPython,代码行数:30,代码来源:server.py

示例3: getattr

# 需要导入模块: from autobahn.twisted.wamp import RouterSessionFactory [as 别名]
# 或者: from autobahn.twisted.wamp.RouterSessionFactory import add [as 别名]
   ## if asked to start an embedded application component ..
   ##
   if args.component:
      ## dynamically load the application component ..
      ##
      import importlib
      c = args.component.split('.')
      mod, klass = '.'.join(c[:-1]), c[-1]
      app = importlib.import_module(mod)
      SessionKlass = getattr(app, klass)

      ## .. and create and add an WAMP application session to
      ## run next to the router
      ##
      from autobahn.wamp import types
      session_factory.add(SessionKlass(types.ComponentConfig(realm = args.realm)))


   if args.transport == "websocket":

      ## create a WAMP-over-WebSocket transport server factory with longpoll fallback
      ##
      from autobahn.wamp.serializer import JsonSerializer, MsgPackSerializer
      from autobahn.twisted.websocket import WampWebSocketServerFactory
      from autobahn.twisted.resource import WebSocketResource
      from twisted.web.server import Site
      from twisted.web.static import File
      from autobahn.wamp.http import WampHttpResource
      ws_factory = WampWebSocketServerFactory(session_factory, debug_wamp = args.debug)
      ws_factory.setProtocolOptions(failByDrop = False)
      serializers = [MsgPackSerializer(), JsonSerializer()]
开发者ID:arnoschn,项目名称:AutobahnPython,代码行数:33,代码来源:server.py

示例4: RouterFactory

# 需要导入模块: from autobahn.twisted.wamp import RouterSessionFactory [as 别名]
# 或者: from autobahn.twisted.wamp.RouterSessionFactory import add [as 别名]
    # create a WAMP router factory
    ##
    from autobahn.twisted.wamp import RouterFactory
    router_factory = RouterFactory()

    # create a WAMP router session factory
    ##
    from autobahn.twisted.wamp import RouterSessionFactory
    session_factory = RouterSessionFactory(router_factory)
    session_factory.session = MyRouterSession

    # start an embedded application component ..
    ##
    component_config = types.ComponentConfig(realm="realm1")
    component_session = TimeService(component_config)
    session_factory.add(component_session)

    # create a WAMP-over-WebSocket transport server factory
    ##
    from autobahn.twisted.websocket import WampWebSocketServerFactory
    transport_factory = WampWebSocketServerFactory(session_factory, args.wsurl, debug=False, debug_wamp=args.debug)
    transport_factory.protocol = ServerProtocol
    transport_factory._cookies = {}

    transport_factory.setProtocolOptions(failByDrop=False)

    from twisted.web.server import Site
    from twisted.web.static import File
    from autobahn.twisted.resource import WebSocketResource

    # we serve static files under "/" ..
开发者ID:AdrianBajdiuk,项目名称:AutobahnPython,代码行数:33,代码来源:server.py

示例5: print

# 需要导入模块: from autobahn.twisted.wamp import RouterSessionFactory [as 别名]
# 或者: from autobahn.twisted.wamp.RouterSessionFactory import add [as 别名]
    print("Running on reactor {}".format(reactor))

    ## create a WAMP router factory
    ##
    from autobahn.wamp.router import RouterFactory

    router_factory = RouterFactory()

    ## create a WAMP router session factory
    ##
    from autobahn.twisted.wamp import RouterSessionFactory

    session_factory = RouterSessionFactory(router_factory)

    ## [ ... ... ]
    session_factory.add(PubSubComponent())

    ## create a WAMP-over-WebSocket transport server factory
    ##
    from autobahn.twisted.websocket import WampWebSocketServerFactory

    # NB: args.wsurl MUST NOT INCLUDE a path; hence it is not really a URL; all it supports is protocol (which must be ws or wss), hostname, and port. anything after that gives a mysterious
    #   File "/usr/lib/python2.7/site-packages/autobahn/websocket/protocol.py", line 3383, in setSessionParameters
    # raise Exception("path specified for server WebSocket URL")
    transport_factory = WampWebSocketServerFactory(session_factory, args.wsurl, debug=True)
    transport_factory.setProtocolOptions(failByDrop=False)

    ## start the WebSocket server from an endpoint
    ##
    server = serverFromString(reactor, args.websocket)
    server.listen(transport_factory)
开发者ID:kousu,项目名称:modex,代码行数:33,代码来源:server.py

示例6: RouterFactory

# 需要导入模块: from autobahn.twisted.wamp import RouterSessionFactory [as 别名]
# 或者: from autobahn.twisted.wamp.RouterSessionFactory import add [as 别名]
   ## create a WAMP router factory
   ##
   from autobahn.wamp.router import RouterFactory
   router_factory = RouterFactory()


   ## create a WAMP router session factory
   ##
   from autobahn.twisted.wamp import RouterSessionFactory
   session_factory = RouterSessionFactory(router_factory)
   session_factory.session = MyRouterSession


   ## start an embedded application component ..
   ##
   session_factory.add(TimeService())


   ## create a WAMP-over-WebSocket transport server factory
   ##
   from autobahn.twisted.websocket import WampWebSocketServerFactory
   transport_factory = WampWebSocketServerFactory(session_factory, args.wsurl, debug_wamp = args.debug)
   transport_factory.protocol = ServerProtocol
   transport_factory._cookies = {}

   transport_factory.setProtocolOptions(failByDrop = False)


   from twisted.web.server import Site
   from twisted.web.static import File
   from autobahn.twisted.resource import WebSocketResource
开发者ID:EricSchles,项目名称:AutobahnPython,代码行数:33,代码来源:server.py

示例7: RouterFactory

# 需要导入模块: from autobahn.twisted.wamp import RouterSessionFactory [as 别名]
# 或者: from autobahn.twisted.wamp.RouterSessionFactory import add [as 别名]
                                    debug = debug,
                                    debugCodePaths = True)
   ctl_endpoint.protocol = CtlProtocol
   

   from autobahn.wamp.router import RouterFactory
   router_factory = RouterFactory()

     
   ## create a WAMP router session factory
   ##
   from autobahn.twisted.wamp import RouterSessionFactory
   session_factory = RouterSessionFactory(router_factory)
   
   ## [ ... ... ]
   session_factory.add(ModelServer())
   
   ## create a WAMP-over-WebSocket transport server factory
   ##
   from autobahn.twisted.websocket import WampWebSocketServerFactory
   wamp_factory = WampWebSocketServerFactory(session_factory, "ws://localhost:8080", debug = True)
   wamp_factory.setProtocolOptions(failByDrop = False)
   
   
   webroot = pathjoin(PROJECT_ROOT,"src","frontend")
   assets = pathjoin(PROJECT_ROOT,"assets")
   if debug:
     print "putting", webroot,"at root"
     print "putting", assets,"at assets"
   
   
开发者ID:sunshineplur,项目名称:modex,代码行数:31,代码来源:server.py

示例8: test_minimal

# 需要导入模块: from autobahn.twisted.wamp import RouterSessionFactory [as 别名]
# 或者: from autobahn.twisted.wamp.RouterSessionFactory import add [as 别名]
      def test_minimal(self):

         embedded_components, client_components = [], [Case2_Backend, Case2_Frontend]

         ## create a WAMP router factory
         ##
         router_factory = RouterFactory()


         ## create a WAMP router session factory
         ##
         session_factory = RouterSessionFactory(router_factory)



         ## .. and create and add an WAMP application session to
         ## run next to the router
         ##
         config = types.ComponentConfig(realm = self.realm,
            extra = {
               'caselog': 'case1.log'
            }
         )
         try:
            log = io.open('caselog.log', 'w')
         except Exception as e:
            print(e)
            return
   #      log = io.open(config.extra['caselog'], 'w')
         config.log = log
         config.dlog = []
         config.components = []

         config.all_done = []

         for C in embedded_components:
            one_done = Deferred()
            config.all_done.append(one_done)
            c = C(config, one_done)
            config.components.append(c)
            session_factory.add(c)

         if self.transport == "websocket":

            ## create a WAMP-over-WebSocket transport server factory
            ##
            transport_factory = WampWebSocketServerFactory(session_factory, debug_wamp = self.debug)
            transport_factory.setProtocolOptions(failByDrop = False, openHandshakeTimeout = 0, closeHandshakeTimeout = 0)

         elif self.transport in ['rawsocket-json', 'rawsocket-msgpack']:

            ## create a WAMP-over-RawSocket transport server factory
            ##
            if self.transport == 'rawsocket-msgpack':
               serializer = MsgPackSerializer()
            elif self.transport == 'rawsocket-json':
               serializer = JsonSerializer()
            else:
               raise Exception("should not arrive here")

            transport_factory = WampRawSocketServerFactory(session_factory, serializer, debug = self.debug)

         else:
            raise Exception("should not arrive here")


         ## start the server from an endpoint
         ##
         from twisted.internet import reactor
         server = serverFromString(reactor, self.server)
         d = server.listen(transport_factory)

         def onlisten(port):
            config.port = port

         d.addCallback(onlisten)

         clients = []
         clients_d = []
         for C in client_components:
            ## create a WAMP application session factory
            ##
            session_factory = ApplicationSessionFactory(config)

            one_done = Deferred()
            config.all_done.append(one_done)

            def make_make(Klass, done):
               def make(config):
                  c = Klass(config, done)
                  config.components.append(c)
                  return c
               return make

            ## .. and set the session class on the factory
            ##
            session_factory.session = make_make(C, one_done)

            if self.transport == "websocket":

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

示例9: start_webserver

# 需要导入模块: from autobahn.twisted.wamp import RouterSessionFactory [as 别名]
# 或者: from autobahn.twisted.wamp.RouterSessionFactory import add [as 别名]
def start_webserver(options, protocol=vtk_wamp.ServerProtocol, disableLogging=False):
    """
    Starts the web-server with the given protocol. Options must be an object
    with the following members:
        options.host : the interface for the web-server to listen on
        options.port : port number for the web-server to listen on
        options.timeout : timeout for reaping process on idle in seconds
        options.content : root for web-pages to serve.
    """
    from twisted.internet import reactor
    from twisted.web.server import Site
    from twisted.web.static import File
    import sys

    if not disableLogging:
        log.startLogging(sys.stdout)

    contextFactory = None

    use_SSL = False
    if options.sslKey and options.sslCert:
      use_SSL = True
      wsProtocol = "wss"
      from twisted.internet import ssl
      contextFactory = ssl.DefaultOpenSSLContextFactory(options.sslKey, options.sslCert)
    else:
      wsProtocol = "ws"

    # Create WAMP router factory
    from autobahn.wamp.router import RouterFactory
    router_factory = RouterFactory()

    # create a WAMP router session factory
    from autobahn.twisted.wamp import RouterSessionFactory
    session_factory = RouterSessionFactory(router_factory)

    # Register protocol
    session_factory.add(protocol())

    # create a WAMP-over-WebSocket transport server factory
    transport_factory = vtk_wamp.TimeoutWampWebSocketServerFactory(session_factory, \
           url        = "%s://%s:%d" % (wsProtocol, options.host, options.port),    \
           debug      = options.debug,                                              \
           debug_wamp = options.debug,                                              \
           timeout    = options.timeout )

    # Do we serve static content or just websocket ?
    if len(options.content) == 0:
        # Only WebSocket
        listenWS(transport_factory, contextFactory, options.timeout)
    else:
        # Static HTTP + WebSocket
        wsResource = WebSocketResource(transport_factory)

        root = File(options.content)
        root.putChild("ws", wsResource)

        if options.uploadPath != None :
            from upload import UploadPage
            uploadResource = UploadPage(options.uploadPath)
            root.putChild("upload", uploadResource)

        site = Site(root)

        if use_SSL:
          reactor.listenSSL(options.port, site, contextFactory)
        else:
          reactor.listenTCP(options.port, site)

    # Work around to force the output buffer to be flushed
    # This allow the process launcher to parse the output and
    # wait for "Start factory" to know that the WebServer
    # is running.
    if options.forceFlush :
        for i in range(200):
            log.msg("+"*80, logLevel=logging.CRITICAL)

    # Give test client a chance to initialize a thread for itself
    # testing.initialize(opts=options)

    # Initialize testing: checks if we're doing a test and sets it up
    testing.initialize(options, reactor)

    # Start the reactor
    if options.nosignalhandlers:
        reactor.run(installSignalHandlers=0)
    else:
        reactor.run()

    # Give the testing module a chance to finalize, if necessary
    testing.finalize()
开发者ID:cmoxiv,项目名称:VTK,代码行数:93,代码来源:server.py

示例10: __init__

# 需要导入模块: from autobahn.twisted.wamp import RouterSessionFactory [as 别名]
# 或者: from autobahn.twisted.wamp.RouterSessionFactory import add [as 别名]
class Node:
   """
   A Crossbar.io node is the running a controller process
   and one or multiple worker processes.

   A single Crossbar.io node runs exactly one instance of
   this class, hence this class can be considered a system
   singleton.
   """

   def __init__(self, reactor, cbdir, debug = False):
      """
      Ctor.

      :param reactor: Reactor to run on.
      :type reactor: obj
      :param cbdir: Crossbar.io node directory to run from.
      :type cbdir: str
      """
      self.debug = debug

      self._reactor = reactor
      self._cbdir = cbdir
      self._worker_processes = {}

      ## node name: FIXME
      self._node_name = "{}-{}".format(socket.getfqdn(), os.getpid())
      self._node_name.replace('-', '_')
      self._node_name = '918234'

      ## node management
      self._management_url = "ws://127.0.0.1:7000"
      #self._management_url = "wss://cloud.crossbar.io"
      self._management_realm = "crossbar.cloud.aliceblue"

      ## load Crossbar.io node configuration
      ##
      cf = os.path.join(self._cbdir, 'config.json')
      with open(cf, 'rb') as infile:
         self._config = json.load(infile)


   def start(self):
      """
      Starts this node. This will start a node controller
      and then spawn new worker processes as needed.

      The node controller will watch spawned processes,
      communicate via stdio with the worker, and start
      and restart the worker processes as needed.
      """
      ## the node controller singleton WAMP application session
      ##
      self._node_controller_session = NodeControllerSession(self)

      ## router and factory that creates router sessions
      ##
      self._router_factory = RouterFactory()
      self._router_session_factory = RouterSessionFactory(self._router_factory)

      ## add the node controller singleton session to the router
      ##
      self._router_session_factory.add(self._node_controller_session)

      if True:
         ## create a WAMP-over-WebSocket transport server factory
         ##
         from autobahn.twisted.websocket import WampWebSocketServerFactory
         from twisted.internet.endpoints import serverFromString

         self._router_server_transport_factory = WampWebSocketServerFactory(self._router_session_factory, "ws://localhost:9000", debug = False)
         self._router_server_transport_factory.setProtocolOptions(failByDrop = False)


         ## start the WebSocket server from an endpoint
         ##
         self._router_server = serverFromString(self._reactor, "tcp:9000")
         self._router_server.listen(self._router_server_transport_factory)

      ## factory that creates router session transports. these are for clients
      ## that talk WAMP-WebSocket over pipes with spawned worker processes and
      ## for any uplink session to a management service
      ##
      self._router_client_transport_factory = WampWebSocketClientFactory(self._router_session_factory, "ws://localhost", debug = False)
      self._router_client_transport_factory.setProtocolOptions(failByDrop = False)

      if False:
         management_session_factory = ApplicationSessionFactory()
         management_session_factory.session = NodeManagementSession
         management_session_factory.node_controller_session = node_controller_session
         management_transport_factory = WampWebSocketClientFactory(management_session_factory, "ws://127.0.0.1:7000")
         management_transport_factory.setProtocolOptions(failByDrop = False)
         management_client = clientFromString(self._reactor, "tcp:127.0.0.1:7000")
         management_client.connect(management_transport_factory)


      ## startup the node from configuration file
      ##
      self._node_controller_session.run_node_config(self._config)
开发者ID:darioodiaz,项目名称:crossbar,代码行数:101,代码来源:node.py

示例11: install_reactor

# 需要导入模块: from autobahn.twisted.wamp import RouterSessionFactory [as 别名]
# 或者: from autobahn.twisted.wamp.RouterSessionFactory import add [as 别名]
   reactor = install_reactor()
   if args.debug:
      print("Running on reactor {}".format(reactor))


   ## create a WAMP router factory
   ##
   from autobahn.wamp.router import RouterFactory
   router_factory = RouterFactory()


   ## create a WAMP router session factory
   ##
   from autobahn.twisted.wamp import RouterSessionFactory
   session_factory = RouterSessionFactory(router_factory)
   session_factory.add(TestService())


   from autobahn.wamp.serializer import MsgPackSerializer
   serializer = MsgPackSerializer()

   from autobahn.twisted.rawsocket import WampRawSocketClientFactory, WampRawSocketClientProtocol
   transport_factory = WampRawSocketClientFactory(session_factory, serializer, debug = args.debug)

   class WorkerClientProtocol(WampRawSocketClientProtocol):

      def connectionMade(self):
         WampRawSocketClientProtocol.connectionMade(self)


      def connectionLost(self, reason):
开发者ID:anton-matosov,项目名称:AutobahnCpp,代码行数:33,代码来源:stdio_server.py

示例12: __init__

# 需要导入模块: from autobahn.twisted.wamp import RouterSessionFactory [as 别名]
# 或者: from autobahn.twisted.wamp.RouterSessionFactory import add [as 别名]
class Node:
   """
   A Crossbar.io node is the running a controller process
   and one or multiple worker processes.

   A single Crossbar.io node runs exactly one instance of
   this class, hence this class can be considered a system
   singleton.
   """

   def __init__(self, reactor, options):
      """
      Ctor.

      :param reactor: Reactor to run on.
      :type reactor: obj
      :param options: Options from command line.
      :type options: obj
      """
      self.debug = False

      self.options = options
      ## the reactor under which we run
      self._reactor = reactor

      ## shortname for reactor to run (when given via explicit option) or None
      self._reactor_shortname = options.reactor

      ## node directory
      self._cbdir = options.cbdir

      ## the node's name (must be unique within the management realm)
      self._node_id = None

      ## the node's management realm
      self._realm = None

      ## node controller session (a singleton ApplicationSession embedded
      ## in the node's management router)
      self._controller = None



   def start(self):
      """
      Starts this node. This will start a node controller and then spawn new worker
      processes as needed.
      """
      ## for now, a node is always started from a local configuration
      ##
      configfile = os.path.join(self.options.cbdir, self.options.config)
      log.msg("Starting from local configuration '{}'".format(configfile))
      config = checkconfig.check_config_file(configfile, silence = True)

      self.start_from_config(config)



   def start_from_config(self, config):

      controller_config = config.get('controller', {})

      controller_options = controller_config.get('options', {})

      controller_title = controller_options.get('title', 'crossbar-controller')

      try:
         import setproctitle
      except ImportError:
         log.msg("Warning, could not set process title (setproctitle not installed)")
      else:
         setproctitle.setproctitle(controller_title)


      ## the node's name (must be unique within the management realm)
      if 'id' in controller_config:
         self._node_id = controller_config['id']
      else:
         self._node_id = socket.gethostname()

      ## the node's management realm
      self._realm = controller_config.get('realm', 'crossbar')


      ## the node controller singleton WAMP application session
      ##
      #session_config = ComponentConfig(realm = options.realm, extra = options)

      self._controller = NodeControllerSession(self)

      ## router and factory that creates router sessions
      ##
      self._router_factory = RouterFactory(
         options = wamp.types.RouterOptions(uri_check = wamp.types.RouterOptions.URI_CHECK_LOOSE),
         debug = False)
      self._router_session_factory = RouterSessionFactory(self._router_factory)

      ## add the node controller singleton session to the router
      ##
      self._router_session_factory.add(self._controller)
#.........这里部分代码省略.........
开发者ID:Inspire2Innovate,项目名称:crossbar,代码行数:103,代码来源:node.py

示例13: install_reactor

# 需要导入模块: from autobahn.twisted.wamp import RouterSessionFactory [as 别名]
# 或者: from autobahn.twisted.wamp.RouterSessionFactory import add [as 别名]
    from autobahn.twisted.choosereactor import install_reactor
    reactor = install_reactor()
    if args.debug:
        print("Running on reactor {}".format(reactor))

    # create a WAMP router factory
    ##
    from autobahn.wamp.router import RouterFactory
    router_factory = RouterFactory()

    # create a WAMP router session factory
    from autobahn.twisted.wamp import RouterSessionFactory
    session_factory = RouterSessionFactory(router_factory)
    session_factory.session = WebServiceLoginRouterSession

    session_factory.add(TimeService(args.realm))

    # create a WAMP-over-WebSocket transport server factory
    transport_factory = WampWebSocketServerFactory(
        session_factory, args.wsurl, debug_wamp=args.debug)
    #transport_factory.protocol = ServerProtocol

    transport_factory.setProtocolOptions(failByDrop=False)

    from twisted.web.server import Site
    from twisted.web.static import File
    from autobahn.twisted.resource import WebSocketResource

    # we serve static files under "/" ..
    root = File(".")
开发者ID:mcfletch,项目名称:AutobahnPython,代码行数:32,代码来源:server.py

示例14: TestEmbeddedSessions

# 需要导入模块: from autobahn.twisted.wamp import RouterSessionFactory [as 别名]
# 或者: from autobahn.twisted.wamp.RouterSessionFactory import add [as 别名]
class TestEmbeddedSessions(unittest.TestCase):
   """
   Test cases for application session running embedded in router.
   """

   def setUp(self):
      """
      Setup router and router session factories.
      """
      if USE_ASYNCIO:
         self.loop = asyncio.new_event_loop()
         asyncio.set_event_loop(self.loop)

      self.router_factory = RouterFactory()
      self.session_factory = RouterSessionFactory(self.router_factory)


   def tearDown(self):
      if USE_ASYNCIO:
         self.loop.close()
         asyncio.set_event_loop(None)
         gc.collect()


   def test_add(self):
      """
      Create an application session and add it to a router to
      run embedded.
      """
      d = FutureMixin._create_future()

      class TestSession(ApplicationSession):

         def onJoin(self, details):
            FutureMixin._resolve_future(d, None)

      session = TestSession(types.ComponentConfig('realm1'))

      self.session_factory.add(session)

      if USE_ASYNCIO:
         self.loop.run_until_complete(d)
      elif USE_TWISTED:
         return d
      else:
         raise Exception("logic error")


   def test_add_and_subscribe(self):
      """
      Create an application session that subscribes to some
      topic and add it to a router to run embedded.
      """
      d = FutureMixin._create_future()

      class TestSession(ApplicationSession):

         def onJoin(self, details):
            def on_event(*arg, **kwargs):
               pass

            d2 = self.subscribe(on_event, u'com.example.topic1')

            def ok(_):
               FutureMixin._resolve_future(d, None)
            def error(err):
               FutureMixin._reject_future(d, err)

            FutureMixin._add_future_callbacks(d2, ok, error)

      session = TestSession(types.ComponentConfig('realm1'))

      self.session_factory.add(session)

      if USE_ASYNCIO:
         self.loop.run_until_complete(d)
      elif USE_TWISTED:
         return d
      else:
         raise Exception("logic error")
开发者ID:0004c,项目名称:VTK,代码行数:82,代码来源:test_router.py

示例15: run

# 需要导入模块: from autobahn.twisted.wamp import RouterSessionFactory [as 别名]
# 或者: from autobahn.twisted.wamp.RouterSessionFactory import add [as 别名]
def run():
    import sys, argparse
    from twisted.python import log
    from twisted.internet.endpoints import serverFromString

    ## parse command line arguments
    ##

    def_wsocket = 'ws://127.0.0.1:8080/ws'
    def_realm = 'realm1'
    def_topic_base = 'sys'
    def_dsn = 'dbname=autobahn host=localhost user=autouser'
    def_endpoint='tcp:8080'
    def_engine = 'PG9_4'

    p = argparse.ArgumentParser(description="basicrouter example with database")

    p.add_argument('-w', '--websocket', action='store', dest='wsocket', default=def_wsocket,
                        help='web socket '+def_wsocket)
    p.add_argument('-r', '--realm', action='store', dest='realm', default=def_realm,
                        help='connect to websocket using "realm", default '+def_realm)
    p.add_argument('-v', '--verbose', action='store_true', dest='verbose',
            default=False, help='Verbose logging for debugging')
    p.add_argument('--debug', action='store_true', dest='debug',
            default=False, help='Autobahn layer debugging')
    p.add_argument('-e', '--engine', action='store', dest='engine', default=def_engine,
                        help='if specified, a database engine will be attached. Note engine is rooted on --topic')
    p.add_argument("--endpoint", type = str, default = "tcp:8080",
          help = 'Twisted server endpoint descriptor, e.g. "tcp:8080" or "unix:/tmp/mywebsocket", default is "' + def_endpoint + '"')
    p.add_argument('-d', '--dsn', action='store', dest='dsn', default=def_dsn,
                        help='if specified the database in dsn will be connected and ready')
    p.add_argument('-t', '--topic', action='store', dest='topic_base', default=def_topic_base,
                        help='if you specify --dsn then you will need a topic to root it on, the default ' + def_topic_base + ' is fine.')

    args = p.parse_args()
    if args.verbose:
        log.startLogging(sys.stdout)

    ## we use an Autobahn utility to install the "best" available Twisted reactor
    ##
    from autobahn.twisted.choosereactor import install_reactor
    reactor = install_reactor()
    log.msg("Running on reactor {}".format(reactor))

    # database workers...
    userdb = UserDb(topic_base=args.topic_base+'.db',debug=args.verbose)
    sessiondb = SessionDb(topic_base=args.topic_base,debug=args.verbose)

    ## create a WAMP router factory
    ##
    component_config = types.ComponentConfig(realm = args.realm)

    from autobahn.twisted.wamp import RouterFactory
    router_factory = RouterFactory()
    authorization_session = AuthorizeSession(component_config,
        topic_base=args.topic_base+'.db',debug=args.verbose,db=sessiondb,router=AuthorizeRouter)
    router_factory.router = authorization_session.ret_func

    ## create a WAMP router session factory
    ##
    from autobahn.twisted.wamp import RouterSessionFactory
    session_factory = RouterSessionFactory(router_factory)
    session_factory.session = MyRouterSession

    log.msg("session_factory.session")

    session_factory.userdb = userdb
    session_factory.sessiondb = sessiondb

    log.msg("userdb, sessiondb")

    sessiondb_component = SessionData(component_config,session_factory.sessiondb,
        topic_base=args.topic_base)
    session_factory.add(sessiondb_component)
    session_factory.add(authorization_session)

    log.msg("session_factory")

    db_session = DB(component_config, engine=args.engine,
        topic_base=args.topic_base+'.db', dsn=args.dsn, debug=args.verbose)
    session_factory.add(db_session)
    session_factory.userdb.set_session(db_session)
    session_factory.sessiondb.set_session(db_session)

    ## create a WAMP-over-WebSocket transport server factory
    ##
    from autobahn.twisted.websocket import WampWebSocketServerFactory
    transport_factory = WampWebSocketServerFactory(session_factory, debug = args.debug)
    transport_factory.setProtocolOptions(failByDrop = False)


    ## start the server from an endpoint
    ##
    ## this address clash detection was a goody I got from stackoverflow:
    ## http://stackoverflow.com/questions/12007316/exiting-twisted-application-after-listenfailure
    server = serverFromString(reactor, args.endpoint)
    def listen():
        srv = server.listen(transport_factory)
        def ListenFailed(reason):
            log.msg("On Startup Listen Failed with {}".format(reason))
#.........这里部分代码省略.........
开发者ID:lgfausak,项目名称:sqlauth,代码行数:103,代码来源:sqlauthrouter.py


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