public PeerSubscriptionCache(Fiber fiber, Scheduler scheduler, SubscriptionObserver observer)
		{
			_observer = observer;
			_fiber = fiber;
			_scheduler = scheduler;
			_endpoints = new Dictionary<Uri, EndpointSubscriptionCache>();
		}
    static void Main()
    {
        // Log messages from SDK to the console
        Trace.Listeners.Add(new ConsoleTraceListener());

        IRtmClient client = new RtmClientBuilder(endpoint, appkey).Build();

        client.OnEnterConnected += cn => Console.WriteLine("Connected to Satori RTM!");
        client.Start();

        // Create subscription observer to observe channel subscription events
        var observer = new SubscriptionObserver();

        observer.OnSubscriptionData += (ISubscription sub, RtmSubscriptionData data) =>
        {
            foreach (JToken jToken in data.Messages)
            {
                Console.WriteLine("Got message: " + jToken);
            }
        };

        client.CreateSubscription(channel, SubscriptionModes.Simple, observer);

        Console.ReadKey();

        // Stop and clean up the client before exiting the program
        client.Dispose().Wait();
    }
        public static async Task <JToken> CreateSubscriptionAndWaitSubscribed(
            this IRtmClient client,
            string channel,
            string position,
            ISubscriptionObserver observer)
        {
            var tcs  = new TaskCompletionSource <JToken>();
            var sobs = new SubscriptionObserver();

            sobs.OnEnterSubscribed += (s) =>
            {
                tcs.TrySetResult(s.Position);
            };
            sobs.OnEnterFailed += (_) =>
            {
                tcs.TrySetException(new Exception("subscription was removed"));
            };
            sobs.OnDeleted += (_) =>
            {
                tcs.TrySetException(new Exception("subscription was removed"));
            };
            var subCfg = new SubscriptionConfig(SubscriptionModes.Advanced)
            {
                Position = position,
                Observer = new SubscriptionCompoundObserver(sobs, observer)
            };

            client.CreateSubscription(channel, subCfg);
            return(await tcs.Task.ConfigureAwait(false));
        }
示例#4
0
        public async Task RepeatSecondMessage()
        {
            var channel = GenerateRandomChannelName();
            var client  = new RtmClientBuilder(Config.Endpoint, Config.AppKey).Build();

            var obs     = new SubscriptionObserver();
            var subData = obs.CreateSubscriptionDataQueue();

            client.Start();

            await client.CreateSubscriptionAndWaitSubscribed(channel, null, obs);

            await client.Publish(channel, "first-message", Ack.Yes).ConfigureAwait(false);

            var pos = (await subData.DequeueAndVerify(channel, "first-message").ConfigureAwait(false)).Position;
            await client.Publish(channel, "second-message", Ack.Yes).ConfigureAwait(false);

            await subData.DequeueAndVerify(channel, "second-message").ConfigureAwait(false);

            client.RemoveSubscription(channel);
            await client.CreateSubscriptionAndWaitSubscribed(channel, pos, obs).ConfigureAwait(false);

            await subData.DequeueAndVerify(channel, "second-message").ConfigureAwait(false);

            client.RemoveSubscription(channel);
            client.Stop();
            await client.Dispose();
        }
示例#5
0
 public BusSubscriptionCache(SubscriptionObserver observer)
 {
     _observer      = observer;
     _subscriptions =
         new ConcurrentCache <SubscriptionKey, BusSubscription>(
             x => new BusSubscription(x.MessageName, x.CorrelationId, _observer));
 }
		public EndpointSubscriptionCache(Fiber fiber, Scheduler scheduler, SubscriptionObserver observer)
		{
			_fiber = fiber;
			_scheduler = scheduler;
			_observer = observer;
			_messageSubscriptions = new Dictionary<string, EndpointSubscription>();
		}
示例#7
0
        static void Main()
        {
            int intIndexOfForLoop = 0;

            // DataStorage.strCryptoCurrencySearchCriteria = View.DrawStartScreen(); //turn off for debug

            Trace.Listeners.Add(new ConsoleTraceListener());
            IRtmClient client = new RtmClientBuilder(endpoint, appkey).Build();

            client.OnEnterConnected += cn => Console.WriteLine("Connected to Data Steam");
            client.Start();
            var observer = new SubscriptionObserver();

            observer.OnSubscriptionData += (ISubscription sub, RtmSubscriptionData data) =>
            {
                foreach (JToken msg in data.Messages)
                {
                    Message msgTempMessage = new Message(ReadToObject(msg.ToString()));

                    Controller.Loop(msgTempMessage, intIndexOfForLoop);

                    intIndexOfForLoop = intIndexOfForLoop + 1;
                }
            };


            client.CreateSubscription(channel, SubscriptionModes.Simple, observer);
            Console.ReadKey();
            client.Dispose().Wait();
        }
示例#8
0
        public async Task RepeatFirstMessage()
        {
            var channel = GenerateRandomChannelName();
            var client  = new RtmClientBuilder(Config.Endpoint, Config.AppKey).Build();
            await client.Yield();

            var subObs  = new SubscriptionObserver();
            var subData = subObs.CreateSubscriptionDataQueue();

            var subscription = new QueueAsync <string>();

            subObs.OnEnterSubscribed += s =>
            {
                subscription.Enqueue(s.Position);
            };

            client.Start();
            client.CreateSubscription(channel, SubscriptionModes.Advanced, subObs);
            var pos = await subscription.Dequeue().ConfigureAwait(false);

            await client.Publish(channel, "message-1", Ack.Yes).ConfigureAwait(false);

            await subData.DequeueAndVerify(channel, "message-1").ConfigureAwait(false);

            await client.Yield();

            client.RemoveSubscription(channel);
            client.CreateSubscription(
                channel,
                new SubscriptionConfig(SubscriptionModes.Advanced, position: pos, observer: subObs));
            await subData.DequeueAndVerify(channel, "message-1").ConfigureAwait(false);

            await client.Dispose();
        }
 public BusSubscriptionCache(SubscriptionObserver observer)
 {
     _observer = observer;
     _subscriptions =
         new ConcurrentCache<SubscriptionKey, BusSubscription>(
             x => new BusSubscription(x.MessageName, x.CorrelationId, _observer));
 }
示例#10
0
        public async Task RestartOnSubscriptionError()
        {
            var trigger = new TaskCompletionSource <bool>();
            var counts  = 3;
            var client  = new RtmClientBuilder(Config.Endpoint, Config.AppKey).Build();
            await client.Yield();

            var obs = new SubscriptionObserver();

            client.CreateSubscription(string.Empty, SubscriptionModes.Advanced, obs);
            obs.OnEnterFailed += (s) =>
            {
                if (counts == 0)
                {
                    trigger.TrySetResult(true);
                }
                else
                {
                    counts -= 1;
                    client.Restart();
                }
            };
            client.Start();
            await trigger.Task;

            client.Stop();
            await client.Dispose();
        }
示例#11
0
		public BusSubscription(string messageName, SubscriptionObserver observer)
		{
			_messageName = messageName;
			_observer = observer;

			_ids = new HashSet<Guid>();

			_subscriptionId = Guid.Empty;
		}
 public EndpointSubscriptionCache(Fiber fiber, Scheduler scheduler, SubscriptionObserver observer)
 {
     _fiber = fiber;
     _scheduler = scheduler;
     _observer = observer;
     _messageSubscriptions =
         new DictionaryCache<SubscriptionKey, EndpointSubscription>(
             key => new EndpointSubscription(_fiber, _scheduler, key.MessageName, key.CorrelationId, _observer));
 }
 public EndpointSubscriptionCache(Fiber fiber, Scheduler scheduler, SubscriptionObserver observer)
 {
     _fiber                = fiber;
     _scheduler            = scheduler;
     _observer             = observer;
     _messageSubscriptions =
         new DictionaryCache <SubscriptionKey, EndpointSubscription>(
             key => new EndpointSubscription(_fiber, _scheduler, key.MessageName, key.CorrelationId, _observer));
 }
示例#14
0
        public BusSubscription(string messageName, string correlationId, SubscriptionObserver observer)
        {
            _messageName   = messageName;
            _correlationId = correlationId;
            _observer      = observer;

            _ids = new HashSet <Guid>();

            _subscriptionId = Guid.Empty;
        }
示例#15
0
        public PeerHandler(Fiber fiber, Scheduler scheduler, Inbox inbox, SubscriptionObserver observer)
        {
            _observer = observer;
            _endpointSubscriptionCache = new EndpointSubscriptionCache(fiber, scheduler, observer);

            inbox.Receive<InitializePeerHandler>(init =>
                {
                    _peerId = init.PeerId;
                    _peerUri = init.PeerUri;
                });
        }
示例#16
0
        public PeerHandler(Fiber fiber, Scheduler scheduler, Inbox inbox, SubscriptionObserver observer)
        {
            _observer = observer;
            _endpointSubscriptionCache = new EndpointSubscriptionCache(fiber, scheduler, observer);

            inbox.Receive <InitializePeerHandler>(init =>
            {
                _peerId  = init.PeerId;
                _peerUri = init.PeerUri;
            });
        }
示例#17
0
        public PeerCache(SubscriptionObserver observer, Guid clientId, Uri controlUri, SubscriptionRepository repository)
        {
            _peers = new DictionaryCache<Uri, ActorRef>();
            _peerUri = controlUri;
            _peerIds = new DictionaryCache<Guid, Uri>();

            _peerHandlerFactory = ActorFactory.Create((f, s, i) => new PeerHandler(i, observer, repository));

            // create a peer for our local client
            WithPeer(clientId, controlUri, x => { }, true);
        }
示例#18
0
        public PeerCache(SubscriptionObserver observer, Guid clientId, Uri controlUri, SubscriptionRepository repository)
        {
            _peers   = new DictionaryCache <Uri, ActorRef>();
            _peerUri = controlUri;
            _peerIds = new DictionaryCache <Guid, Uri>();

            _peerHandlerFactory = ActorFactory.Create((f, s, i) => new PeerHandler(i, observer, repository));

            // create a peer for our local client
            WithPeer(clientId, controlUri, x => { }, true);
        }
 public EndpointSubscriptionCache(SubscriptionObserver observer, Uri peerUri,
     SubscriptionRepository repository)
 {
     _observer = observer;
     _peerUri = peerUri;
     _messageSubscriptions =
         new DictionaryCache<SubscriptionKey, EndpointSubscription>(
             key =>
             new EndpointSubscription(_peerUri, key.MessageName, key.CorrelationId, _observer,
                 repository));
 }
 public EndpointSubscriptionCache(SubscriptionObserver observer, Uri peerUri,
                                  SubscriptionRepository repository)
 {
     _observer             = observer;
     _peerUri              = peerUri;
     _messageSubscriptions =
         new DictionaryCache <SubscriptionKey, EndpointSubscription>(
             key =>
             new EndpointSubscription(_peerUri, key.MessageName, key.CorrelationId, _observer,
                                      repository));
 }
		public EndpointSubscription(Fiber fiber, Scheduler scheduler, string messageName,
		                            SubscriptionObserver observer)
		{
			_fiber = fiber;
			_scheduler = scheduler;
			_messageName = messageName;
			_observer = observer;

			_ids = new Dictionary<Guid, PeerSubscription>();

			_subscriptionId = Guid.Empty;
		}
示例#22
0
    static void Main()
    {
        // Log messages from SDK to the console
        Trace.Listeners.Add(new ConsoleTraceListener());

        IRtmClient client = new RtmClientBuilder(endpoint, appkey).Build();

        client.OnEnterConnected += cn => Console.WriteLine("Connected to Satori RTM!");

        client.OnError += ex =>
                          Console.WriteLine("Failed to connect: " + ex.Message);

        client.Start();

        var observer = new SubscriptionObserver();

        observer.OnEnterSubscribed += (ISubscription sub) =>
                                      Console.WriteLine("Subscribed to: " + sub.SubscriptionId);

        observer.OnLeaveSubscribed += (ISubscription sub) =>
                                      Console.WriteLine("Unsubscribed from: " + sub.SubscriptionId);

        observer.OnSubscriptionData += (ISubscription sub, RtmSubscriptionData data) =>
        {
            foreach (JToken jToken in data.Messages)
            {
                Console.WriteLine("Got message: " + jToken);
            }
        };

        observer.OnSubscribeError += (ISubscription sub, Exception err) =>
                                     Console.WriteLine("Failed to subscribe: " + err.Message);

        observer.OnSubscriptionError += (ISubscription sub, RtmSubscriptionError err) =>
                                        Console.WriteLine("Subscription failed. RTM sent the unsolicited error {0}: {1}", err.Code, err.Reason);

        client.CreateSubscription("animals", SubscriptionModes.Simple, observer);

        client.RemoveSubscription("animals");

        var cfg = new SubscriptionConfig(SubscriptionModes.Simple, observer)
        {
            Filter = "SELECT * FROM `animals` WHERE who LIKE 'z%'"
        };

        client.CreateSubscription("animals", cfg);

        Console.ReadKey();

        // Stop and clean up the client before exiting the program
        client.Dispose().Wait();
    }
示例#23
0
        public async Task TwoClients()
        {
            var channel    = GenerateRandomChannelName();
            int i          = 0;
            var msg        = $"message-{i++}";
            var subscriber = (RtmClient) new RtmClientBuilder(Config.Endpoint, Config.AppKey).Build();

            var publisher = new RtmClientBuilder(Config.Endpoint, Config.AppKey).Build();

            publisher.Start();
            subscriber.Start();

            var subObs  = new SubscriptionObserver();
            var subData = subObs.CreateSubscriptionDataQueue();
            await subscriber.CreateSubscriptionAndWaitSubscribed(channel, null, subObs).ConfigureAwait(false);

            await publisher.Publish(channel, msg, Ack.Yes).ConfigureAwait(false);

            await subData.DequeueAndVerify(channel, msg).ConfigureAwait(false);

            subscriber.Stop();
            if ((await subscriber.GetStateAsync()).GetConnection() != null)
            {
                throw new Exception("test failed");
            }

            do
            {
                msg = $"message-{i++}";
                await publisher.Publish(channel, msg, Ack.Yes).ConfigureAwait(false);

                await Task.Delay(500);

                RtmSubscriptionData data;
                if (subData.TryDequeue(out data))
                {
                    throw new Exception("test failed");
                }

                subscriber.Start();

                await subData.DequeueAndVerify(channel, msg).ConfigureAwait(false);

                subscriber.Stop();
                GC.Collect();
            } while (i < 3);

            await subscriber.Dispose();

            publisher.Stop();
            await publisher.Dispose();
        }
示例#24
0
        public EndpointSubscription(Uri peerUri, string messageName, string correlationId,
                                    SubscriptionObserver observer, SubscriptionRepository repository)
        {
            _peerUri       = peerUri;
            _messageName   = messageName;
            _correlationId = correlationId;
            _observer      = observer;
            _repository    = repository;

            _ids = new Dictionary <Guid, PeerSubscription>();

            _subscriptionId = Guid.Empty;
        }
        public EndpointSubscription(Fiber fiber, Scheduler scheduler, string messageName, string correlationId,
                                    SubscriptionObserver observer)
        {
            _fiber         = fiber;
            _scheduler     = scheduler;
            _messageName   = messageName;
            _correlationId = correlationId;
            _observer      = observer;

            _ids = new Dictionary <Guid, PeerSubscription>();

            _subscriptionId = Guid.Empty;
        }
示例#26
0
        public EndpointSubscription(Uri peerUri, string messageName, string correlationId,
            SubscriptionObserver observer, SubscriptionRepository repository)
        {
            _peerUri = peerUri;
            _messageName = messageName;
            _correlationId = correlationId;
            _observer = observer;
            _repository = repository;

            _ids = new Dictionary<Guid, PeerSubscription>();

            _subscriptionId = Guid.Empty;
        }
示例#27
0
        public PeerCache(Fiber fiber, Scheduler scheduler, SubscriptionObserver observer, Guid clientId,
                         Uri controlUri)
        {
            _peers     = new DictionaryCache <Uri, ActorRef>();
            _peerUri   = controlUri;
            _fiber     = fiber;
            _scheduler = scheduler;
            _peerIds   = new DictionaryCache <Guid, Uri>();

            _peerHandlerFactory = ActorFactory.Create((f, s, i) => new PeerHandler(f, s, i, observer));

            // create a peer for our local client
            WithPeer(clientId, controlUri, x => { }, true);
        }
示例#28
0
        public PeerHandler(Inbox inbox, SubscriptionObserver observer,
            SubscriptionRepository repository)
        {
            _observer = observer;

            inbox.Receive<InitializePeerHandler>(init =>
                {
                    _peerId = init.PeerId;
                    _peerUri = init.PeerUri;

                    _endpointSubscriptionCache = new EndpointSubscriptionCache(observer, _peerUri,
                        repository);
                });
        }
示例#29
0
        public PeerCache(Fiber fiber, Scheduler scheduler, SubscriptionObserver observer, Guid clientId,
                         Uri controlUri)
        {
            _peers = new DictionaryCache<Uri, ActorRef>();
            _peerUri = controlUri;
            _fiber = fiber;
            _scheduler = scheduler;
            _peerIds = new DictionaryCache<Guid, Uri>();

            _peerHandlerFactory = ActorFactory.Create((f, s, i) => new PeerHandler(f, s, i, observer));

            // create a peer for our local client
            WithPeer(clientId, controlUri, x => { }, true);
        }
示例#30
0
    static async Task Async(IRtmClient client)
    {
        RtmPublishReply reply = null;

        try
        {
            var message = new Animal
            {
                Who   = "zebra",
                Where = new float[] { 34.134358f, -118.321506f }
            };

            reply = await client.Publish("animals", message, Ack.Yes);

            Console.WriteLine("Publish confirmed");
        }
        catch (Exception ex)
        {
            Console.WriteLine("Failed to publish: " + ex.Message);
        }

        var observer = new SubscriptionObserver();

        observer.OnEnterSubscribed += (ISubscription sub) =>
                                      Console.WriteLine("Subscribed to: " + sub.SubscriptionId);

        observer.OnLeaveSubscribed += (ISubscription sub) =>
                                      Console.WriteLine("Unsubscribed from: " + sub.SubscriptionId);

        observer.OnSubscriptionData += (ISubscription sub, RtmSubscriptionData data) =>
        {
            foreach (JToken jToken in data.Messages)
            {
                Console.WriteLine("Got message: " + jToken);
            }
        };

        observer.OnSubscribeError += (ISubscription sub, Exception err) =>
                                     Console.WriteLine("Failed to subscribe: " + err.Message);

        observer.OnSubscriptionError += (ISubscription sub, RtmSubscriptionError err) =>
                                        Console.WriteLine("Subscription failed. RTM sent the unsolicited error {0}: {1}", err.Code, err.Reason);

        var cfg = new SubscriptionConfig(SubscriptionModes.Simple, observer)
        {
            Position = reply?.Position
        };

        client.CreateSubscription("animals", cfg);
    }
示例#31
0
        public PeerHandler(Inbox inbox, SubscriptionObserver observer,
                           SubscriptionRepository repository)
        {
            _observer = observer;

            inbox.Receive <InitializePeerHandler>(init =>
            {
                _peerId  = init.PeerId;
                _peerUri = init.PeerUri;

                _endpointSubscriptionCache = new EndpointSubscriptionCache(observer, _peerUri,
                                                                           repository);
            });
        }
示例#32
0
        public void MultiSubjectProxy_Untyped_AsObserver_AsSubscription()
        {
            Run(client =>
            {
                var env = new TestExecutionEnvironment();
                var ctx = client.CreateContext(env);

                var uri      = new Uri("test://subject");
                var observer = new SubscriptionObserver <int>();
                var subject  = new TestSubject(observer);
                env.AddArtifact(uri, subject);

                var proxy = new MultiSubjectProxy(uri);
                var sub   = SubscribeRoot(new Never <int>(), proxy.GetObserver <int>());
                new SubscriptionInitializeVisitor(sub).Initialize(ctx);
                Assert.IsTrue(observer.IsAcceptCalled);

                sub.Dispose();
                Assert.IsTrue(observer.IsDisposeCalled);
            });
        }
 public BusSubscriptionCache(SubscriptionObserver observer)
 {
     _observer = observer;
     _subscriptions = new Dictionary<SubscriptionKey, BusSubscription>();
 }
		public void AddObserver(SubscriptionObserver observer)
		{
			lock (_observers)
				_observers.Add(observer);
		}
		public BusSubscriptionCache(SubscriptionObserver observer)
		{
			_observer = observer;
			_subscriptions = new ReaderWriterLockedDictionary<string, BusSubscription>();
		}
示例#36
0
 public void AddObserver(SubscriptionObserver observer)
 {
     lock (_observers)
         _observers.Add(observer);
 }
示例#37
0
    // Use this for initialization
    void Start()
    {
        var textObj = GameObject.Find("text");

        mesh      = (Text)textObj.GetComponent(typeof(Text));
        mesh.text = "";

        // Change logging levels. Default level is Warning.
        DefaultLoggers.Dispatcher.SetLevel(Logger.LogLevel.Verbose);
        DefaultLoggers.Serialization.SetLevel(Logger.LogLevel.Verbose);
        DefaultLoggers.Connection.SetLevel(Logger.LogLevel.Verbose);
        DefaultLoggers.Client.SetLevel(Logger.LogLevel.Verbose);
        DefaultLoggers.ClientRtm.SetLevel(Logger.LogLevel.Verbose);
        DefaultLoggers.ClientRtmSubscription.SetLevel(Logger.LogLevel.Verbose);

        try
        {
            ShowText(string.Format("RTM connection config:\n\tendpoint='{0}'\n\tappkey='{1}'", endpoint, appKey));

            //check if the role is set to authenticate or not
            var toAuthenticate = !new string[] { "YOUR_ROLE", "", null }.Contains(role);
            ShowText(string.Format("Starting RTM client... Authenticate? {0} (role={1})", toAuthenticate, role));

            if (toAuthenticate)
            {
                client = RtmManager.Instance.Register(endpoint, appKey, role, roleSecretKey);
            }
            else
            {   //no authentication (default role)
                client = RtmManager.Instance.Register(endpoint, appKey);
            }

            // Hook up to client connectivity state transitions
            client.OnEnterConnecting += () => ShowText("Connecting...");
            client.OnEnterConnected  += cn => ShowText("Connected to Satori RTM!");
            client.OnLeaveConnected  += cn => ShowText("Disconnected");
            client.OnError           += ex => ShowText("ERROR:\n" + ex);

            // We create a subscription observer object to receive callbacks
            // for incoming messages, subscription state changes and errors.
            // The same observer can be shared between several subscriptions.
            var observer = new SubscriptionObserver();

            observer.OnSubscribeError += (sub, ex) =>
            {
                ShowText("ERROR: subscribing failed. " +
                         "Check channel subscribe permissions in Dev Portal. \n" + ex);
            };

            // when subscription is establshed (confirmed by RTM)
            observer.OnEnterSubscribed += sub =>
            {
                ShowText("Subscribed to " + sub.SubscriptionId);

                // Instruct the Update method to publish next message.
                // We publish a message to the same channel we have subscribed to
                // and so will be receiving our own message.
                // (This is a contrived example just for tutorial purposes)
                publishAnimal = true;
            };

            // when the subscription ends
            observer.OnLeaveSubscribed += sub => ShowText("Unsubscribed from " + sub.SubscriptionId);

            // when a subscription error occurs
            observer.OnSubscriptionError += (ISubscription sub, RtmSubscriptionError err)
                                            => ShowText("ERROR: subscription " + err.Code + ": " + err.Reason);

            // when messages arrive
            observer.OnSubscriptionData += (ISubscription sub, RtmSubscriptionData data) =>
            {
                // Note: sub.SubscriptionId is the channel name
                ShowText("Message received from channel " + sub.SubscriptionId);

                // Messages arrive in an array
                foreach (JToken jToken in data.Messages)
                {
                    ShowText(jToken.ToString());
                    Animal msg  = jToken.ToObject <Animal>();
                    string text = string.Format("Who? {0}. Where? at {1},{2}", msg.who, msg.where[0], msg.where[1]);
                    ShowText(text);
                }
            };

            // At this point, the client may not yet be connected to Satori RTM.
            // If the client is not connected, the SDK internally queues the subscription request and
            // will send it once the client connects
            client.CreateSubscription(channel, observer);
        }
        catch (System.UriFormatException uriEx)
        {
            ShowText("ERRROR: invalid connection credentials. Check endpoint and appkey");
        }
        catch (Exception ex)
        {
            ShowText("ERROR: setting up RTM client failed.\n" + ex);
        }
    }
示例#38
0
        public BusSubscriptionEventListener(IServiceBus bus, SubscriptionObserver observer)
        {
            _endpointUri = bus.Endpoint.Address.Uri;

            _busSubscriptionCache = new BusSubscriptionCache(observer);
        }
示例#39
0
    static void Main()
    {
        // Log messages from SDK to the console
        Trace.Listeners.Add(new ConsoleTraceListener());

        // Change logging levels to increase verbosity. Default level is Warning.
        DefaultLoggers.Dispatcher.SetLevel(Logger.LogLevel.Warning);
        DefaultLoggers.Serialization.SetLevel(Logger.LogLevel.Warning);
        DefaultLoggers.Connection.SetLevel(Logger.LogLevel.Warning);
        DefaultLoggers.Client.SetLevel(Logger.LogLevel.Warning);
        DefaultLoggers.ClientRtm.SetLevel(Logger.LogLevel.Warning);
        DefaultLoggers.ClientRtmSubscription.SetLevel(Logger.LogLevel.Warning);

        //check if the role is set to authenticate or not
        var toAuthenticate = !new string[] { "YOUR_ROLE", "", null }.Contains(role);

        Console.WriteLine("RTM connection config:\n" +
                          "\tendpoint='{0}'\n" +
                          "\tappkey='{1}'\n" +
                          "\tauthenticate?={2}", endpoint, appKey, toAuthenticate);

        var builder = new RtmClientBuilder(endpoint, appKey);

        if (toAuthenticate)
        {
            builder.SetRoleSecretAuthenticator(role, roleSecretKey);
        }

        IRtmClient client = builder.Build();

        // Hook up to client lifecycle events
        client.OnEnterConnected += cn => Console.WriteLine("Connected to Satori RTM!");
        client.OnError          += ex => Console.WriteLine("RTM client failed: " + ex.Message);

        client.Start();

        // We create a subscription observer object to receive callbacks
        // for incoming messages, subscription state changes and errors.
        // The same observer can be shared between several subscriptions.
        var observer = new SubscriptionObserver();

        // when subscription is established (confirmed by RTM)
        observer.OnEnterSubscribed += sub =>
                                      Console.WriteLine("Subscribed to the channel: " + sub.SubscriptionId);;

        observer.OnSubscribeError += (sub, ex) =>
                                     Console.WriteLine("Subscribing failed. " +
                                                       "Check channel subscribe permissions in Dev Portal. \n" + ex.Message);

        observer.OnSubscriptionError += (ISubscription sub, RtmSubscriptionError err)
                                        => Console.WriteLine("Subscription error " + err.Code + ": " + err.Reason);

        observer.OnSubscriptionData += (ISubscription sub, RtmSubscriptionData data) =>
        {
            // Messages arrive in an array
            foreach (JToken jToken in data.Messages)
            {
                try
                {
                    Animal msg = jToken.ToObject <Animal>();
                    Console.WriteLine("Got animal {0}: {1}", msg.Who, jToken);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Failed to handle the incoming message: {0}", ex.Message);
                }
            }
        };

        // At this point, the client may not yet be connected to Satori RTM.
        // If the client is not connected, the SDK internally queues the subscription request and
        // will send it once the client connects
        client.CreateSubscription(channel, SubscriptionModes.Simple, observer);

        PublishLoop(client).Wait();
    }
示例#40
0
    static void Main()
    {
        // Log messages from SDK to the console
        Trace.Listeners.Add(new ConsoleTraceListener());

        IRtmClient client = new RtmClientBuilder(endpoint, appkey).Build();

        client.OnEnterConnected += cn => Console.WriteLine("Connected to Satori RTM!");

        client.OnError += ex =>
                          Console.WriteLine("Failed to connect: " + ex.Message);

        client.Start();

        var observer = new SubscriptionObserver();

        observer.OnEnterSubscribed += (ISubscription sub) =>
                                      Console.WriteLine("Subscribed to: " + sub.SubscriptionId);

        observer.OnLeaveSubscribed += (ISubscription sub) =>
                                      Console.WriteLine("Unsubscribed from: " + sub.SubscriptionId);

        observer.OnSubscriptionData += (ISubscription sub, RtmSubscriptionData data) =>
        {
            foreach (JToken jToken in data.Messages)
            {
                try
                {
                    Animal msg = jToken.ToObject <Animal>();
                    Console.WriteLine("Got animal {0}: {1}", msg.Who, jToken);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Failed to handle the incoming message: {0}", ex.Message);
                }
            }
        };

        observer.OnSubscribeError += (ISubscription sub, Exception err) =>
        {
            var rtmEx = err as SubscribeException;
            if (rtmEx != null)
            {
                Console.WriteLine("Failed to subscribe. RTM replied with the error {0}: {1}", rtmEx.Error.Code, rtmEx.Error.Reason);
            }
            else
            {
                Console.WriteLine("Failed to subscribe: " + err.Message);
            }
        };

        observer.OnSubscriptionError += (ISubscription sub, RtmSubscriptionError err) =>
                                        Console.WriteLine("Subscription failed. RTM sent the unsolicited error {0}: {1}", err.Code, err.Reason);

        client.CreateSubscription("animals", SubscriptionModes.Simple, observer);

        Console.ReadKey();

        // Stop and clean up the client before exiting the program
        client.Dispose().Wait();
    }