예제 #1
0
def RegisterWampClient(wampconf):

    WSClientConf = LoadWampClientConf(wampconf)

    # start logging to console
    # log.startLogging(sys.stdout)

    # create a WAMP application session factory
    component_config = types.ComponentConfig(realm=WSClientConf["realm"],
                                             extra={"ID": WSClientConf["ID"]})
    session_factory = wamp.ApplicationSessionFactory(config=component_config)
    session_factory.session = WampSession

    # create a WAMP-over-WebSocket transport client factory
    transport_factory = ReconnectingWampWebSocketClientFactory(
        session_factory,
        url=WSClientConf["url"],
        serializers=[MsgPackSerializer()],
        debug=False,
        debug_wamp=False)

    # start the client from a Twisted endpoint
    conn = connectWS(transport_factory)
    print("WAMP client connecting to :", WSClientConf["url"])
    return conn
    def _connect(self):
        if self.client:
            self.logger.debug('already connected to broadcaster %s' % self.url)
            return
        broadcaster = self
        self.logger.debug('trying to connect to broadcaster %s' % self.url)

        class BroadcasterComponent(wamp.ApplicationSession):
            def onJoin(self, details):
                broadcaster.client = self
                broadcaster.onSessionOpen()

            def onDisconnect(self):
                broadcaster.logger.debug(
                    "Disconnected from broadcaster at %s, will reconnect" %
                    broadcaster.host)
                broadcaster.client = None

        component_config = types.ComponentConfig(realm="yadt")
        session_factory = wamp.ApplicationSessionFactory(
            config=component_config)
        session_factory.session = BroadcasterComponent
        serializers = [JsonSerializer()]
        transport_factory = websocket.WampWebSocketClientFactory(
            session_factory,
            serializers=serializers,
            url="ws://{0}:{1}/wamp".format(self.host, self.port),
            debug=False,
            debug_wamp=False)
        client = clientFromString(reactor,
                                  "tcp:{0}:{1}".format(self.host, self.port))
        from functools import partial
        client.connect(transport_factory).addErrback(
            partial(broadcaster.logger.warning,
                    "Could not connect to broadcaster at %s"))
예제 #3
0
    def _prepare_transport(self):
        ''' Prepare a transport factory '''
        assert self._reactor, \
            'WAMPFrontend: cannot create transport without an IOLoop and a TornadoReactor'

        config = types.ComponentConfig(
            realm = self.config['wampfrontend']['realm'],
            extra = {
                'name': self.config['wampfrontend']['name'],
                'core': self.core,
                'frontend': self })
        session = wamp.ApplicationSessionFactory(config=config)
        session.session = WAMPFrontendComponent

        # Add a reference toe the frontend object (ourself)
        session._frontend = self
        
        # Add a reference the the ApplicationSession created
        # since we are a client, there will be only one session at all
        session._client = None

        # Now also store a reference to the session factory for us
        self._session = session
        
        transport = MyClientFactory(
            session,
            url = self.config['wampfrontend']['router'],
            debug = self.config['wampfrontend']['debug_autobahn'],
            debug_wamp = self.config['wampfrontend']['debug_wamp'])
        return transport
예제 #4
0
def RegisterWampClient(wampconf, secretfname):

    WSClientConf = LoadWampClientConf(wampconf)

    if not WSClientConf:
        print(_("WAMP client connection not established!"))
        return

    WampSecret = LoadWampSecret(secretfname)

    if WampSecret is not None:
        WSClientConf["secret"] = WampSecret

    # create a WAMP application session factory
    component_config = types.ComponentConfig(realm=WSClientConf["realm"],
                                             extra=WSClientConf)
    session_factory = wamp.ApplicationSessionFactory(config=component_config)
    session_factory.session = WampSession

    # create a WAMP-over-WebSocket transport client factory
    transport_factory = ReconnectingWampWebSocketClientFactory(
        session_factory,
        url=WSClientConf["url"],
        serializers=[MsgPackSerializer()])

    # start the client from a Twisted endpoint
    conn = connectWS(transport_factory)
    print(_("WAMP client connecting to :"), WSClientConf["url"])
    return conn
예제 #5
0
    def RegisterWampClient():

        ## start logging to console
        # log.startLogging(sys.stdout)

        # create a WAMP application session factory
        component_config = types.ComponentConfig(
            realm = realm,
            extra = {"ID":ID})
        session_factory = wamp.ApplicationSessionFactory(
            config = component_config)
        session_factory.session = WampSession

        # create a WAMP-over-WebSocket transport client factory
        transport_factory = WampWebSocketClientFactory(
            session_factory,
            url = url,
            serializers = [MsgPackSerializer()],
            debug = False,
            debug_wamp = False)

        # start the client from a Twisted endpoint
        conn = connectWS(transport_factory)
        confnodesroot.logger.write(_("WAMP connecting to URL : %s\n")%url)
        return conn
예제 #6
0
def RegisterWampClient(wampconf=None, wampsecret=None):
    global _WampConf, _WampSecret
    _WampConfDefault = os.path.join(WorkingDir, "wampconf.json")
    _WampSecretDefault = os.path.join(WorkingDir, "wamp.secret")

    # set config file path only if not already set
    if _WampConf is None:
        # default project's wampconf has precedance over commandline given
        if os.path.exists(_WampConfDefault) or wampconf is None:
            _WampConf = _WampConfDefault
        else:
            _WampConf = wampconf

    WampClientConf = GetConfiguration()

    # set secret file path only if not already set
    if _WampSecret is None:
        # default project's wamp secret also
        # has precedance over commandline given
        if os.path.exists(_WampSecretDefault):
            _WampSecret = _WampSecretDefault
        else:
            _WampSecret = wampsecret

    if _WampSecret is not None:
        WampClientConf["secret"] = LoadWampSecret(_WampSecret)
    else:
        print(_("WAMP authentication has no secret configured"))
        _WampSecret = _WampSecretDefault

    if not WampClientConf["active"]:
        print(_("WAMP deactivated in configuration"))
        return

    # create a WAMP application session factory
    component_config = types.ComponentConfig(
        realm=WampClientConf["realm"],
        extra=WampClientConf)
    session_factory = wamp.ApplicationSessionFactory(
        config=component_config)
    session_factory.session = WampSession

    # create a WAMP-over-WebSocket transport client factory
    ReconnectingWampWebSocketClientFactory(
        component_config,
        session_factory,
        url=WampClientConf["url"],
        serializers=[MsgPackSerializer()])

    # start the client from a Twisted endpoint
    if _transportFactory:
        connectWS(_transportFactory)
        print(_("WAMP client connecting to :"), WampClientConf["url"])
        return True
    else:
        print(_("WAMP client can not connect to :"), WampClientConf["url"])
        return False
예제 #7
0
def wampConnect(wamp_conf):
    """WAMP connection procedure.

    :param wamp_conf: WAMP configuration from settings.json file

    """

    LOG.info("WAMP connection precedures:")

    try:

        component_config = types.ComponentConfig(
            realm=unicode(wamp_conf['realm'])
        )
        session_factory = wamp.ApplicationSessionFactory(
            config=component_config
        )
        session_factory.session = WampFrontend

        transport_factory = WampClientFactory(
            session_factory,
            url=wamp_conf['url']
        )
        transport_factory.autoPingInterval = 5
        transport_factory.autoPingTimeout = 5

        connector = websocket.connectWS(transport_factory)

        try:

            addr = str(connector.getDestination().host)
            socket.inet_pton(socket.AF_INET, addr)
            LOG.info(" - establishing connection to : " + str(addr))

        except socket.error as err:
            LOG.error(" - IP address validation error: " + str(err))
            Bye()

    except Exception as err:
        LOG.error(" - URI validation error: " + str(err))
        Bye()
예제 #8
0
파일: subscriber.py 프로젝트: urp/bonefish
    @inlineCallbacks
    def onDisconnect(self):
        reactor.stop()

    def onRandomDataEvent(self, i):
        print("Random data event: {}".format(i))


if __name__ == '__main__':
    # Start logging to console
    log.startLogging(sys.stdout)

    ## Create an application session factory
    component_config = types.ComponentConfig(realm="default")
    session_factory = wamp.ApplicationSessionFactory(config=component_config)
    session_factory.session = Component

    # Setup the serializers that we can support
    serializers = []
    #serializers.append(JsonSerializer(batched = True))
    #serializers.append(MsgPackSerializer(batched = True))
    #serializers.append(JsonSerializer())
    serializers.append(MsgPackSerializer())

    # Create a websocket transport factory
    transport_factory = websocket.WampWebSocketClientFactory(
        session_factory, serializers=serializers, debug=False, debug_wamp=True)

    ## Start the client and connect
    client = clientFromString(reactor, "tcp:127.0.0.1:8001")
예제 #9
0
            if self.received > 5:
                self.leave()

        sub = yield self.subscribe(on_event, u'com.myapp.topic1')
        print("Subscribed with subscription ID {}".format(sub.id))

    def onDisconnect(self):
        reactor.stop()


if __name__ == '__main__':

    ## 0) start logging to console
    log.startLogging(sys.stdout)

    ## 1) create a WAMP application session factory
    session_factory = wamp.ApplicationSessionFactory()
    session_factory.session = MyFrontendComponent

    ## 2) create a WAMP-over-WebSocket transport client factory
    transport_factory = websocket.WampWebSocketClientFactory(session_factory, \
                                                             debug = False, \
                                                             debug_wamp = False)

    ## 3) start the client from a Twisted endpoint
    client = clientFromString(reactor, "tcp:127.0.0.1:8080")
    client.connect(transport_factory)

    ## 4) now enter the Twisted reactor loop
    reactor.run()
예제 #10
0
        yield self.subscribe(on_event, 'com.myapp.topic1')

        counter = 0
        while True:
            self.publish('com.myapp.topic1',
                         counter,
                         options=types.PublishOptions(excludeMe=False))
            counter += 1
            yield sleep(1)


if __name__ == '__main__':

    log.startLogging(sys.stdout)

    session_factory = wamp.ApplicationSessionFactory(
        config=types.ComponentConfig(realm="realm1"))
    session_factory.session = MyFrontendComponent

    from autobahn.wamp.serializer import *
    # serializer = JsonSerializer(batched = True)
    # serializer = MsgPackSerializer(batched = True)
    serializer = JsonSerializer()
    # serializer = MsgPackSerializer()

    transport_factory = rawsocket.WampRawSocketClientFactory(
        session_factory, serializer=serializer, debug=True)

    client = clientFromString(reactor, "tcp:127.0.0.1:9000")
    client.connect(transport_factory)

    reactor.run()
예제 #11
0
    parser.add_argument(
        "-r",
        "--realm",
        type=str,
        default="vrplumber",
        help="The WAMP realm to start the component in (if any).")
    return parser


if __name__ == '__main__':
    parser = get_options()
    args = parser.parse_args()
    if args.debug:
        log.startLogging(sys.stdout)

    session_factory = wamp.ApplicationSessionFactory(
        types.ComponentConfig(realm=args.realm))
    session_factory.session = MyFrontendComponent
    username, password = args.auth.split(':', 1)
    session_factory.credentials = {
        'username': username,
        'password': password,
    }
    transport_factory = websocket.WampWebSocketClientFactory(
        session_factory, debug=args.debug, debug_wamp=args.debug)

    from autobahn.twisted.websocket import connectWS
    transport_factory = ReconnectingWampWebSocketClientFactory(
        session_factory,
        url=args.wsurl,
        debug_wamp=args.debug,
    )