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


Python websocket.WampWebSocketClientFactory类代码示例

本文整理汇总了Python中autobahn.twisted.websocket.WampWebSocketClientFactory的典型用法代码示例。如果您正苦于以下问题:Python WampWebSocketClientFactory类的具体用法?Python WampWebSocketClientFactory怎么用?Python WampWebSocketClientFactory使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


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

示例1: getMapUpdaterComponentService

    def getMapUpdaterComponentService(self, url, realm, mapUpdater):
        def create(config):
            try:
                session = MapUpdaterComponent(mapUpdater, config)
            except Exception as e:
                # the app component could not be created .. fatal
                print(e)
            else:
                session.debug_app = True
                return session

        sessionFactory = ApplicationSessionFactory(
            ComponentConfig(realm, None))
        sessionFactory.session = create

        transportFactory = WampWebSocketClientFactory(
            sessionFactory, url=url)
        transportFactory.noisy = False
        transportFactory.autoPingInterval = 30
        transportFactory.autoPingTimeout = 30

        isSecure, host, port, resource, path, params = parseWsUrl(url)

        endpoint = HostnameEndpoint(reactor, host.encode('utf8'), port)
        if isSecure:
            contextFactory = optionsForClientTLS(hostname=host)
            endpoint = wrapClientTLS(contextFactory, endpoint)
        return ClientService(endpoint, transportFactory)
开发者ID:jsza,项目名称:tempus-map-updater,代码行数:28,代码来源:mapupdater_service.py

示例2: __init2__

   def __init2__(self, factory, config):

      ## transport configuration
      self._config = config

      WampWebSocketClientFactory.__init__(self, config)

      self.setProtocolOptions(failByDrop = False)
开发者ID:bihicheng,项目名称:crossbar,代码行数:8,代码来源:protocol.py

示例3: start

   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,代码行数:57,代码来源:node.py

示例4: start_remote_management_client

   def start_remote_management_client(self):
      from crossbar.management import NodeManagementSession

      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)
开发者ID:rogererens,项目名称:crossbar,代码行数:10,代码来源:node.py

示例5: _create_transport_factory

def _create_transport_factory(reactor, transport, session_factory):
    """
    Create a WAMP-over-XXX transport factory.
    """
    if transport.type == u'websocket':
        serializers = _create_transport_serializers(transport)
        factory = WampWebSocketClientFactory(session_factory, url=transport.url, serializers=serializers)

    elif transport.type == u'rawsocket':
        serializer = _create_transport_serializer(transport.serializers[0])
        factory = WampRawSocketClientFactory(session_factory, serializer=serializer)

    else:
        assert(False), 'should not arrive here'

    # set the options one at a time so we can give user better feedback
    for k, v in transport.options.items():
        try:
            factory.setProtocolOptions(**{k: v})
        except (TypeError, KeyError):
            # this allows us to document options as snake_case
            # until everything internally is upgraded from
            # camelCase
            try:
                factory.setProtocolOptions(
                    **{_camel_case_from_snake_case(k): v}
                )
            except (TypeError, KeyError):
                raise ValueError(
                    "Unknown {} transport option: {}={}".format(transport.type, k, v)
                )
    return factory
开发者ID:Hrabal,项目名称:autobahn-python,代码行数:32,代码来源:component.py

示例6: __init__

 def __init__(self, *args, **kwargs):
     WampWebSocketClientFactory.__init__(self, *args, **kwargs)
     self.proto = None
开发者ID:RaitoBezarius,项目名称:crossbar,代码行数:3,代码来源:native.py

示例7: stopFactory

 def stopFactory(self):
     WampWebSocketClientFactory.stopFactory(self)
     if self.proto:
         self.proto.close()
开发者ID:RaitoBezarius,项目名称:crossbar,代码行数:4,代码来源:native.py

示例8: buildProtocol

 def buildProtocol(self, addr):
     self._proto = WampWebSocketClientFactory.buildProtocol(self, addr)
     return self._proto
开发者ID:josephwinston,项目名称:crossbar,代码行数:3,代码来源:protocol.py

示例9: __init__

 def __init__(self, url, **kwargs):
     return WampWebSocketClientFactory.__init__(self, url, **kwargs)
开发者ID:hiveeyes,项目名称:kotori,代码行数:2,代码来源:nodeservice.py

示例10: run

    def run(self, make, start_reactor=True):
        """
        Run the application component.

        :param make: A factory that produces instances of :class:`autobahn.asyncio.wamp.ApplicationSession`
           when called with an instance of :class:`autobahn.wamp.types.ComponentConfig`.
        :type make: callable

        :param start_reactor: if True (the default) this method starts
           the Twisted reactor and doesn't return until the reactor
           stops. If there are any problems starting the reactor or
           connect()-ing, we stop the reactor and raise the exception
           back to the caller.

        :returns: None is returned, unless you specify
            ``start_reactor=False`` in which case the Deferred that
            connect() returns is returned; this will callback() with
            an IProtocol instance, which will actually be an instance
            of :class:`WampWebSocketClientProtocol`
        """
        if start_reactor:
            # only select framework, set loop and start logging when we are asked
            # start the reactor - otherwise we are running in a program that likely
            # already tool care of all this.
            from twisted.internet import reactor
            txaio.use_twisted()
            txaio.config.loop = reactor

            if self.debug or self.debug_app:
                txaio.start_logging(level='debug')
            else:
                txaio.start_logging(level='info')

        isSecure, host, port, resource, path, params = parseWsUrl(self.url)

        # factory for use ApplicationSession
        def create():
            cfg = ComponentConfig(self.realm, self.extra)
            try:
                session = make(cfg)
            except Exception as e:
                if start_reactor:
                    # the app component could not be created .. fatal
                    self.log.error(str(e))
                    reactor.stop()
                else:
                    # if we didn't start the reactor, it's up to the
                    # caller to deal with errors
                    raise
            else:
                session.debug_app = self.debug_app
                return session

        # create a WAMP-over-WebSocket transport client factory
        transport_factory = WampWebSocketClientFactory(create, url=self.url, serializers=self.serializers,
                                                       proxy=self.proxy, debug=self.debug)

        # supress pointless log noise like
        # "Starting factory <autobahn.twisted.websocket.WampWebSocketClientFactory object at 0x2b737b480e10>""
        transport_factory.noisy = False

        # if user passed ssl= but isn't using isSecure, we'll never
        # use the ssl argument which makes no sense.
        context_factory = None
        if self.ssl is not None:
            if not isSecure:
                raise RuntimeError(
                    'ssl= argument value passed to %s conflicts with the "ws:" '
                    'prefix of the url argument. Did you mean to use "wss:"?' %
                    self.__class__.__name__)
            context_factory = self.ssl
        elif isSecure:
            from twisted.internet.ssl import optionsForClientTLS
            context_factory = optionsForClientTLS(host)

        from twisted.internet import reactor
        if self.proxy is not None:
            from twisted.internet.endpoints import TCP4ClientEndpoint
            client = TCP4ClientEndpoint(reactor, self.proxy['host'], self.proxy['port'])
            transport_factory.contextFactory = context_factory
        elif isSecure:
            from twisted.internet.endpoints import SSL4ClientEndpoint
            assert context_factory is not None
            client = SSL4ClientEndpoint(reactor, host, port, context_factory)
        else:
            from twisted.internet.endpoints import TCP4ClientEndpoint
            client = TCP4ClientEndpoint(reactor, host, port)

        d = client.connect(transport_factory)

        # as the reactor shuts down, we wish to wait until we've sent
        # out our "Goodbye" message; leave() returns a Deferred that
        # fires when the transport gets to STATE_CLOSED
        def cleanup(proto):
            if hasattr(proto, '_session') and proto._session is not None:
                if proto._session.is_attached():
                    return proto._session.leave()
                elif proto._session.is_connected():
                    return proto._session.disconnect()

#.........这里部分代码省略.........
开发者ID:goks,项目名称:Winky,代码行数:101,代码来源:wamp.py

示例11: start_component

   def start_component(self, component, router):
      """
      Starts a Class or WAMPlet in this component container.
      """
      if component['type'] == 'wamplet':

         try:
            dist = component['dist']
            name = component['entry']

            if self.debug:
               log.msg("Worker {}: starting WAMPlet '{}/{}' in realm '{}' ..".format(self._pid, dist, name, router['realm']))

            ## make is supposed to make instances of ApplicationSession
            make = pkg_resources.load_entry_point(dist, 'autobahn.twisted.wamplet', name)

         except Exception as e:
            log.msg("Worker {}: failed to import class - {}".format(e))
            raise ApplicationError("crossbar.error.class_import_failed", str(e))
   
      elif component['type'] == 'class':

         try:
            klassname = component['name']

            if self.debug:
               log.msg("Worker {}: starting class '{}' in realm '{}' ..".format(self._pid, klassname, router['realm']))

            import importlib
            c = klassname.split('.')
            mod, kls = '.'.join(c[:-1]), c[-1]
            app = importlib.import_module(mod)

            ## make is supposed to be of class ApplicationSession
            make = getattr(app, kls)

         except Exception as e:
            log.msg("Worker {}: failed to import class - {}".format(e))
            raise ApplicationError("crossbar.error.class_import_failed", str(e))

      else:
         raise ApplicationError("crossbar.error.invalid_configuration", "unknown component type '{}'".format(component['type']))


      def create():
         cfg = ComponentConfig(realm = router['realm'], extra = component.get('extra', None))
         c = make(cfg)
         return c

      ## create a WAMP-over-WebSocket transport client factory
      ##
      from autobahn.twisted.websocket import WampWebSocketClientFactory
      transport_factory = WampWebSocketClientFactory(create, router['url'], debug = self.debug)
      transport_factory.setProtocolOptions(failByDrop = False)

      ## start a WebSocket client from an endpoint
      ##
      from twisted.internet import reactor
      from twisted.internet.endpoints import TCP4ClientEndpoint, SSL4ClientEndpoint, UNIXClientEndpoint
      from twisted.internet.endpoints import clientFromString

      from crossbar.twisted.tlsctx import TlsClientContextFactory


      if False:
         self._client = clientFromString(reactor, router['endpoint'])
      else:
         try:
            endpoint_config = router.get('endpoint')

            ## a TCP4 endpoint
            ##
            if endpoint_config['type'] == 'tcp':

               ## the host to connect ot
               ##
               host = str(endpoint_config['host'])

               ## the port to connect to
               ##
               port = int(endpoint_config['port'])

               ## connection timeout in seconds
               ##
               timeout = int(endpoint_config.get('timeout', 10))

               if 'tls' in endpoint_config:

                  ctx = TlsClientContextFactory()

                  ## create a TLS client endpoint
                  ##
                  self._client = SSL4ClientEndpoint(reactor,
                                                    host,
                                                    port,
                                                    ctx,
                                                    timeout = timeout)
               else:
                  ## create a non-TLS client endpoint
                  ##
#.........这里部分代码省略.........
开发者ID:rogererens,项目名称:crossbar,代码行数:101,代码来源:container.py

示例12: __init__

 def __init__(self, *args, **kwargs):
     self._authrole = kwargs.pop('authrole')
     WampWebSocketClientFactory.__init__(self, *args, **kwargs)
     self.proto = None
开发者ID:crossbario,项目名称:crossbar,代码行数:4,代码来源:native.py

示例13: __init__

 def __init__(self, factory, *args, **kwargs):
     WampWebSocketClientFactory.__init__(self, factory, *args, **kwargs)
     self.protocol_instance = None
     self.base_client = None
开发者ID:arduino-org,项目名称:s4t-iotronic,代码行数:4,代码来源:test_autobahn_wamp_client.py

示例14: getattr


   ## dynamically load the application component ..
   ##
   import importlib
   c = args.component.split('.')
   mod, klass = '.'.join(c[:-1]), c[-1]
   app = importlib.import_module(mod)

   ## .. and set the session class on the factory
   ##
   session_factory.session = getattr(app, klass)


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


   ## start a WebSocket client from an endpoint
   ##
   client = clientFromString(reactor, args.websocket)
   client.connect(transport_factory)


   ## now enter the Twisted reactor loop
   ##
   reactor.run()
开发者ID:alisaifee,项目名称:AutobahnPython,代码行数:28,代码来源:client.py

示例15: start

   def start(self, transport, klassname, realm):
      """
      Dynamically start an application component to run next to the router in "embedded mode".
      """

      ## dynamically load the application component ..
      ##
      try:
         if self.debug:
            log.msg("Worker {}: starting class '{}' in realm '{}' ..".format(self._pid, klassname, realm))

         import importlib
         c = klassname.split('.')
         mod, klass = '.'.join(c[:-1]), c[-1]
         app = importlib.import_module(mod)
         SessionKlass = getattr(app, klass)

      except Exception as e:
         if self.debug:
            log.msg("Worker {}: failed to import class - {}".format(e))
         raise ApplicationError("crossbar.error.class_import_failed", str(e))

      else:
         ## create a WAMP application session factory
         ##
         #from autobahn.twisted.wamp import ApplicationSessionFactory
         #session_factory = ApplicationSessionFactory()
         session_factory = ComponentSessionFactory(realm)
         session_factory.session = SessionKlass

         ## create a WAMP-over-WebSocket transport client factory
         ##
         from autobahn.twisted.websocket import WampWebSocketClientFactory
         transport_factory = WampWebSocketClientFactory(session_factory, transport['url'], debug = self.debug)
         transport_factory.setProtocolOptions(failByDrop = False)

         ## start a WebSocket client from an endpoint
         ##
         from twisted.internet import reactor
         from twisted.internet.endpoints import TCP4ClientEndpoint, SSL4ClientEndpoint, UNIXClientEndpoint
         from twisted.internet.endpoints import clientFromString
         from tlsctx import TlsClientContextFactory


         if False:
            self._client = clientFromString(reactor, transport['endpoint'])
         else:
            try:
               endpoint_config = transport.get('endpoint')

               ## a TCP4 endpoint
               ##
               if endpoint_config['type'] == 'tcp':

                  ## the host to connect ot
                  ##
                  host = str(endpoint_config['host'])

                  ## the port to connect to
                  ##
                  port = int(endpoint_config['port'])

                  ## connection timeout in seconds
                  ##
                  timeout = int(endpoint_config.get('timeout', 10))

                  if 'tls' in endpoint_config:

                     ctx = TlsClientContextFactory()

                     ## create a TLS client endpoint
                     ##
                     self._client = SSL4ClientEndpoint(reactor,
                                                       host,
                                                       port,
                                                       ctx,
                                                       timeout = timeout)
                  else:
                     ## create a non-TLS client endpoint
                     ##
                     self._client = TCP4ClientEndpoint(reactor,
                                                       host,
                                                       port,
                                                       timeout = timeout)

               ## a Unix Domain Socket endpoint
               ##
               elif endpoint_config['type'] == 'unix':

                  ## the path
                  ##
                  path = str(endpoint_config['path'])

                  ## connection timeout in seconds
                  ##
                  timeout = int(endpoint_config['type'].get('timeout', 10))

                  ## create the endpoint
                  ##
                  self._client = UNIXClientEndpoint(reactor, path, timeout = timeout)
#.........这里部分代码省略.........
开发者ID:darioodiaz,项目名称:crossbar,代码行数:101,代码来源:component.py


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