Exemplo n.º 1
0
        private void Connect()
        {
            var factory = new DefaultWampChannelFactory();

            _channel = factory.CreateJsonChannel(_serverAddress, "mtcrossbar");
            var tries = 0;

            while (!_channel.RealmProxy.Monitor.IsConnected)
            {
                try
                {
                    tries++;
                    LogInfo($"Trying to connect to server {_serverAddress }...");
                    _channel.Open().Wait();
                }
                catch (Exception ex)
                {
                    LogError(ex);
                    if (tries > 5)
                    {
                        throw;
                    }
                    LogInfo("Retrying in 5 sec...");
                }
            }
            LogInfo($"Connected to server {_serverAddress}");

            _realmProxy = _channel.RealmProxy;
            _service    = _realmProxy.Services.GetCalleeProxy <IRpcMtFrontend>();

            // Subscribe Notifications
            _notificationSubscription = _realmProxy.Services.GetSubject <NotifyResponse>($"user.updates.{_notificationId}").Subscribe(NotificationReceived);
        }
Exemplo n.º 2
0
        private static IDisposable ClientCode(string serverAddress)
        {
            DefaultWampChannelFactory channelFactory =
                new DefaultWampChannelFactory();

            IWampChannel wampChannel =
                channelFactory.CreateJsonChannel(serverAddress, "realm1");

            wampChannel.Open().Wait();

            ISubject <int> subject =
                wampChannel.RealmProxy.Services.GetSubject <int>("com.myapp.topic1");

            int counter = 0;

            IObservable <long> timer =
                Observable.Timer(TimeSpan.FromMilliseconds(0),
                                 TimeSpan.FromMilliseconds(1000));

            IDisposable disposable =
                timer.Subscribe(x =>
            {
                counter++;
                Console.WriteLine("Publishing to topic 'com.myapp.topic1': " + counter);
                subject.OnNext(counter);
            });

            return(disposable);
        }
Exemplo n.º 3
0
        private async void OpenConnection_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                DefaultWampChannelFactory channelFactory = new DefaultWampChannelFactory();

                IWampChannel channel = channelFactory.CreateJsonChannel(location, "realm1");

                IWampRealmProxy realmProxy = channel.RealmProxy;

                await channel.Open();

                // Host WAMP application components

                // await openTask;
                //openTask.Wait();

                IArgumentsService instance = new ArgumentsService();

                IWampRealmProxy realm = channel.RealmProxy;

                Task <IAsyncDisposable> registrationTask = realm.Services.RegisterCallee(instance);
                // await registrationTask;
                registrationTask.Wait();
            }
            catch (Exception ex)
            {
                MessageBox.Show(WampShared.Misc.GetErrorMessage(ex), "", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Exemplo n.º 4
0
        public void Connect(ClientEnv env)
        {
            SetEnv(env);
            var          factory = new DefaultWampChannelFactory();
            IWampChannel channel = factory.CreateJsonChannel(_serverAddress, "box-options");

            while (!channel.RealmProxy.Monitor.IsConnected)
            {
                try
                {
                    Console.WriteLine($"Trying to connect to server {_serverAddress}...");
                    channel.Open().Wait();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Exception: {0}", ex);
                    Console.WriteLine("Retrying in 5 sec...");
                    Thread.Sleep(5000);
                }
            }
            Console.WriteLine($"Connected to server {_serverAddress}");

            _realmProxy = channel.RealmProxy;
            _service    = _realmProxy.Services.GetCalleeProxy <IRpcMethods>();
        }
Exemplo n.º 5
0
        static async Task Main(string[] args)
        {
            const string url   = "ws://127.0.0.1:8080/ws";
            const string realm = "realm1";

            DefaultWampChannelFactory channelFactory = new DefaultWampChannelFactory();

            IWampClientAuthenticator authenticator = new TicketAuthenticator();
            IWampChannel             channel       = channelFactory.CreateJsonChannel(url, realm, authenticator);

            IWampRealmProxy realmProxy = channel.RealmProxy;

            IWampClientConnectionMonitor monitor = realmProxy.Monitor;

            monitor.ConnectionEstablished += ConnectionEstablished;
            monitor.ConnectionBroken      += ConnectionBroken;

            await channel.Open().ConfigureAwait(false);

            ITimeService proxy = realmProxy.Services.GetCalleeProxy <ITimeService>();

            try
            {
                string now = await proxy.Now();

                Console.WriteLine("call result {0}", now);
            }
            catch (Exception e)
            {
                Console.WriteLine("call error {0}", e);
            }

            Console.ReadLine();
        }
Exemplo n.º 6
0
        public void Start()
        {
            WampChannel = new DefaultWampChannelFactory().CreateJsonChannel(Helper.ApiUrlWssBase, "realm1");
            WampChannel.RealmProxy.Monitor.ConnectionBroken += OnConnectionBroken;

            WampChannelOpenTask = WampChannel.Open();
        }
Exemplo n.º 7
0
        private static void ClientCode(string serverAddress, MethodInfo sampleMethod)
        {
            JTokenJsonBinding binding = new JTokenJsonBinding();

            DefaultWampChannelFactory factory =
                new DefaultWampChannelFactory();

            IWampChannel channel =
                factory.CreateChannel(serverAddress, "realm1", binding);

            Task task = channel.Open();

            task.Wait(5000);

            if (!task.IsCompleted)
            {
                Console.WriteLine("Server might be down.");
                Console.WriteLine("Press any key to exit...");
                Console.ReadLine();
                Environment.Exit(0);
            }
            else
            {
                Console.WriteLine("Connected to server.");
            }

            sampleMethod.Invoke(null, new object[] { channel.RealmProxy.Services });

            Console.ReadLine();
        }
Exemplo n.º 8
0
        /// <summary>
        ///     The main program entry-point.
        /// </summary>
        static void Main()
        {
            SynchronizationContext.SetSynchronizationContext(
                new SynchronizationContext()
                );

            Console.WriteLine($"Connecting to '{ServerAddress}'...");

            DefaultWampChannelFactory channelFactory = new DefaultWampChannelFactory();
            IWampChannel channel = channelFactory.CreateJsonChannel(ServerAddress, "realm1");

            channel.Open().Wait();

            Console.WriteLine("Connected. Type stuff and press enter (or a blank line to quit).");

            ISubject <string> lineSubject = channel.RealmProxy.Services.GetSubject <string>("io.tintoy.topic1");

            lineSubject.Subscribe(
                message => Console.WriteLine("[MESSAGE] '{0}'", message),
                error => Console.WriteLine("[ERROR] '{0}'", error),
                () => Console.WriteLine("[COMPLETED]")
                );

            string currentLine;

            while ((currentLine = Console.ReadLine()) != "")
            {
                lineSubject.OnNext(currentLine);
            }
        }
Exemplo n.º 9
0
        public static void Main(string[] args)
        {
            DefaultWampChannelFactory factory =
                new DefaultWampChannelFactory();

            const string serverAddress = "ws://127.0.0.1:8080/ws";

            IWampChannel channel =
                factory.CreateJsonChannel(serverAddress, "realm1");

            channel.Open().Wait(5000);

            IWampRealmProxy realmProxy = channel.RealmProxy;

            int         received     = 0;
            IDisposable subscription = null;

            subscription =
                realmProxy.Services.GetSubject <int>("com.myapp.topic1")
                .Subscribe(x =>
            {
                Console.WriteLine("Got Event: " + x);

                received++;

                if (received > 5)
                {
                    Console.WriteLine("Closing ..");
                    subscription.Dispose();
                }
            });

            Console.ReadLine();
        }
Exemplo n.º 10
0
        public void Connect(ClientEnv env)
        {
            SetEnv(env);
            var factory = new DefaultWampChannelFactory();

            _channel = factory.CreateJsonChannel(_serverAddress, "mtcrossbar");

            while (!_channel.RealmProxy.Monitor.IsConnected)
            {
                try
                {
                    Console.WriteLine($"Trying to connect to server {_serverAddress}...");
                    _channel.Open().Wait();
                }
                catch
                {
                    Console.WriteLine("Retrying in 5 sec...");
                    Thread.Sleep(5000);
                }
            }
            Console.WriteLine($"Connected to server {_serverAddress}");

            _realmProxy = _channel.RealmProxy;
            _service    = _realmProxy.Services.GetCalleeProxy <IRpcMtFrontend>();
        }
Exemplo n.º 11
0
        static void Main(string[] args)
        {
            DefaultWampChannelFactory channelFactory = new DefaultWampChannelFactory();

            IWampChannel <JToken> channel =
                channelFactory.CreateChannel("ws://127.0.0.1:9000/");

            channel.Open();

            ICalculator proxy = channel.GetRpcProxy <ICalculator>();

            int five = proxy.Add(2, 3);

            Console.WriteLine("2 + 3 = " + five);

            IAsyncCalculator asyncProxy =
                channel.GetRpcProxy <IAsyncCalculator>();

            Task <int> asyncFive =
                asyncProxy.Add(2, 3);

            Console.WriteLine("2 + 3 = " + asyncFive.Result);

            Console.ReadLine();
        }
Exemplo n.º 12
0
        private static async Task <IWampChannel> ConnectAsync(AppArguments appArguments)
        {
            var factory = new DefaultWampChannelFactory();
            IWampClientAuthenticator clientAuthenticator = GetClientAuthenticator(appArguments.AuthMethod, appArguments.AuthId);

            var channel = clientAuthenticator == null
                ? factory.CreateJsonChannel(GetUri(appArguments), appArguments.Realm)
                : factory.CreateJsonChannel(GetUri(appArguments), appArguments.Realm, clientAuthenticator);

            while (!channel.RealmProxy.Monitor.IsConnected)
            {
                try
                {
                    Console.WriteLine($"Trying to connect to the server {appArguments.Uri}...");

                    channel.Open().Wait();
                }
                catch (Exception e)
                {
                    Console.WriteLine($"Failed to connect: {e.Message}");
                    Console.WriteLine("Retrying in 5 sec...");

                    await Task.Delay(TimeSpan.FromSeconds(5));
                }
            }

            return(channel);
        }
Exemplo n.º 13
0
        public void Init(string wsuri, string realm)
        {
            _factory = new DefaultWampChannelFactory();

            _channel = _factory.CreateJsonChannel(wsuri, realm);

            try
            {
                _channel.Open().Wait();

                services = _channel.RealmProxy.Services;

                // register procedures for remote calling
                services.RegisterCallee(this).Wait();

                // publishing
                onPublishSystemStatusSubject = services.GetSubject <RPiHomeSecurityStatus>("com.rpihomesecurity.onstatus");

                monitor = _channel.RealmProxy.Monitor;
                monitor.ConnectionBroken += OnClose;
                monitor.ConnectionError  += OnError;

                IsConnected = true;
                Console.WriteLine("WAMP connection success");
            }
            catch (Exception e)
            {
                Console.WriteLine("Failure to Initialise WAMP connection. Is crossbar started?" + e.Message);
            }
        }
Exemplo n.º 14
0
        public void Start()
        {
            WampChannel = new DefaultWampChannelFactory().CreateJsonChannel(Helper.ApiUrlWssBase, "realm1");
            WampChannel.RealmProxy.Monitor.ConnectionBroken += OnConnectionBroken;

            WampChannelOpenTask = WampChannel.Open();
        }
Exemplo n.º 15
0
        static void Main(string[] args)
        {
            //Sample modeled and compatible with Autobahn Python https://github.com/tavendo/AutobahnPython [examples/twisted/wamp1/authentication/client.py]

            JsonSerializer            serializer     = new JsonSerializer();
            JsonFormatter             formatter      = new JsonFormatter(serializer);
            DefaultWampChannelFactory channelFactory = new DefaultWampChannelFactory(serializer);
            IWampChannel <JToken>     channel        = channelFactory.CreateChannel("ws://127.0.0.1:9000/");

            channel.Open();

            try
            {
                IWampCraProcedures proxy = channel.GetRpcProxy <IWampCraProcedures>();

                //TODO: This can authenticates as a user, or as anonymous based on conditional.
                WampCraPermissions permissions;
                if (true)
                {
                    permissions = Authenticate(proxy, formatter, "foobar", null, "secret");
                }
                else
                {
                    permissions = Authenticate(proxy, formatter, null, null, null);
                }

                Console.WriteLine("permissions: {0}", formatter.Serialize(permissions));
            }
            catch (WampRpcCallException ex)
            {
                Console.Out.WriteLine("Authenticate WampRpcCallException: '{0}' to uri '{1}'", ex.Message,
                                      ex.ProcUri);
            }

            try
            {
                //Expect failure if running against default server sample and anonymous.

                ISample proxy  = channel.GetRpcProxy <ISample>();
                string  result = proxy.Hello("Foobar");
                Console.WriteLine(result);
            }
            catch (WampRpcCallException ex)
            {
                Console.Out.WriteLine("Hello WampRpcCallException: '{0}' to uri '{1}'", ex.Message,
                                      ex.ProcUri);
            }

            //server sample allows for subscribe for anon and foobar user.
            ISubject <string> subject     = channel.GetSubject <string>("http://example.com/topics/mytopic1");
            IDisposable       cancelation = subject.Subscribe(x => Console.WriteLine("mytopic1: " + x));

            //server sample does not allow for publish if anon.  Therefore, if logged in, expect to see
            // this in console, otherwise it will silently fail to publish (Wamp1 makes it silent).
            subject.OnNext("Hello World From Client!");

            Console.ReadLine();
            channel.Close();
        }
        public void Dispose()
        {
            this.Disconnect();

            this._factory    = null;
            this._channel    = null;
            this._parameters = null;
        }
Exemplo n.º 17
0
        static void Main(string[] args)
        {
            //Sample modeled and compatible with Autobahn Python https://github.com/tavendo/AutobahnPython [examples/twisted/wamp1/authentication/client.py]

            JsonFormatter formatter = new JsonFormatter();
            DefaultWampChannelFactory channelFactory = new DefaultWampChannelFactory(formatter);
            IWampChannel<JToken> channel = channelFactory.CreateChannel("ws://localhost:9000/");

            channel.Open();

            try
            {
                IWampCraProcedures proxy = channel.GetRpcProxy<IWampCraProcedures>();

                //TODO: This can authenticates as a user, or as anonymous based on conditional.
                WampCraPermissions permissions;
                if (true)
                {
                    permissions = Authenticate(proxy, formatter, "foobar", null, "secret");
                }
                else
                {
                    permissions = Authenticate(proxy, formatter, null, null, null);
                }

                Console.WriteLine("permissions: {0}", formatter.Serialize(permissions));
            }
            catch (WampRpcCallException ex)
            {
                Console.Out.WriteLine("Authenticate WampRpcCallException: '{0}' to uri '{1}'", ex.Message,
                                      ex.ProcUri);
            }

            try
            {
                //Expect failure if running against default server sample and anonymous.

                ISample proxy = channel.GetRpcProxy<ISample>();
                string result = proxy.Hello("Foobar");
                Console.WriteLine(result);
            }
            catch (WampRpcCallException ex)
            {
                Console.Out.WriteLine("Hello WampRpcCallException: '{0}' to uri '{1}'", ex.Message,
                                      ex.ProcUri);
            }

            //server sample allows for subscribe for anon and foobar user.
            ISubject<string> subject = channel.GetSubject<string>("http://example.com/topics/mytopic1");
            IDisposable cancelation = subject.Subscribe(x => Console.WriteLine("mytopic1: " + x));

            //server sample does not allow for publish if anon.  Therefore, if logged in, expect to see
            // this in console, otherwise it will silently fail to publish (Wamp1 makes it silent).
            subject.OnNext("Hello World From Client!");

            Console.ReadLine();
            channel.Close();
        }
Exemplo n.º 18
0
        public static int Main(string[] args)
        {
            if (args.Length == 0)
            {
                Console.WriteLine("Wrong number of arguments. Expected: <client id> <server address> <realm> <topic>.");
                return(-1);
            }

            var apiKey = args[0];

            if (args.Length > 1)
            {
                _serverAddress = args[1];
            }
            if (args.Length > 2)
            {
                _realm = args[2];
            }
            if (args.Length > 3)
            {
                _topicUri = args[3];
            }

            var factory       = new DefaultWampChannelFactory();
            var authenticator = new TicketAuthenticator(apiKey);
            var channel       = factory.CreateJsonChannel(_serverAddress, _realm, authenticator);

            channel.RealmProxy.Monitor.ConnectionBroken      += Monitor_ConnectionBroken;
            channel.RealmProxy.Monitor.ConnectionError       += Monitor_ConnectionError;
            channel.RealmProxy.Monitor.ConnectionEstablished += Monitor_ConnectionEstablished;

            while (!channel.RealmProxy.Monitor.IsConnected)
            {
                try
                {
                    Console.WriteLine($"Trying to connect to server {_serverAddress}...");
                    channel.Open().Wait();
                }
                catch
                {
                    Console.WriteLine($"Retrying in {RetryTimeout}...");
                    Thread.Sleep(RetryTimeout);
                }
            }
            Console.WriteLine($"Connected to server {channel}");
            using (Subscribe(channel.RealmProxy))
            {
                Console.WriteLine($"Subscribed to events. ClientId: {apiKey}");
                Console.ReadKey();
            }
            Console.ReadKey();
            channel.Close();
            Console.WriteLine("Terminated");
            return(0);
        }
Exemplo n.º 19
0
        static void Main(string[] args)
        {
            const string location = "ws://127.0.0.1:8080/";

            DefaultWampChannelFactory channelFactory = new DefaultWampChannelFactory();

            IWampChannel channel = channelFactory.CreateJsonChannel(location, "realm1");

            IWampRealmProxy realmProxy = channel.RealmProxy;

            //await
            //channel.Open ();

            // Host WAMP application components

            Task openTask = channel.Open();

            // await openTask;
            openTask.Wait(5000);


            Console.WriteLine("Press enter when a client finishes registering methods");
            Console.ReadLine();
            IArgumentsService proxy = channel.RealmProxy.Services.GetCalleeProxy <IArgumentsService> ();

            proxy.Ping();
            Console.WriteLine("Pinged!");

            int result = proxy.Add2(2, 3);

            Console.WriteLine("Add2: {0}", result);

            var starred = proxy.Stars();

            Console.WriteLine("Starred 1: {0}", starred);

            starred = proxy.Stars(nick: "Homer");
            Console.WriteLine("Starred 2: {0}", starred);

            starred = proxy.Stars(stars: 5);
            Console.WriteLine("Starred 3: {0}", starred);

            starred = proxy.Stars(nick: "Homer", stars: 5);
            Console.WriteLine("Starred 4: {0}", starred);

            // string[] orders = proxy.Orders ("coffee");
            // Console.WriteLine ("Orders 1: {0}", string.Join (", ", orders));

            // orders = proxy.Orders ("coffee", limit : 10);
            // Console.WriteLine ("Orders 2: {0}", string.Join (", ", orders));

            Console.ReadLine();
        }
Exemplo n.º 20
0
 public void Start()
 {
     try {
         WampChannel = new DefaultWampChannelFactory().CreateJsonChannel(Helper.ApiUrlWssBase, "realm1");
         WampChannel.RealmProxy.Monitor.ConnectionBroken += OnConnectionBroken;
         WampChannel.RealmProxy.Monitor.ConnectionError  += OnConnectionError;
         WampChannelOpenTask = WampChannel.Open();
     }
     catch (Exception e) {
         Console.WriteLine("WAMP EXCEPTION (Start): " + e.Message);
     }
 }
Exemplo n.º 21
0
        public void SubscribeAndWait(int workTimeMillis = 85)
        {
            var factory = new DefaultWampChannelFactory();
            var binding = new JTokenMsgpackBinding();

            var channel = factory.CreateChannel("realm", new WebSocket4NetBinaryConnection <JToken>(Configs.ServerAddress, binding), binding);

            try
            {
                channel.Open().Wait();
                //
                for (var i = 0; i < Configs.N_SUBJECTS; i++)
                {
                    string topicUri = Configs.SUBJECT_ + i;
                    channel.RealmProxy.Services.GetSubject <WsEvent>(topicUri).Subscribe(
                        @event =>
                    {
                        Interlocked.Add(ref EventsConsumed, 1);
                        //
                        if (@event.Id % 100 == 0)
                        {
                            Logger.Info("Client #" + _id + ". Processing event #" + @event.Id);
                        }
                        //
                        Thread.Sleep(workTimeMillis);
                    },
                        ex =>
                    {
                        Logger.Error($"Error during {topicUri} subscription", ex);
                    });
                }
                //
                while (!_shouldTerminate())
                {
                    Thread.Sleep(1);
                }
            }
            catch (Exception ex)
            {
                Logger.Error("Error in Client #" + _id, ex);
                // ReSharper disable once LocalizableElement
                MessageBox.Show("Error in Client #" + _id + "\r\n\r\n" + ex, "Error");
                Application.Exit();
            }
            finally
            {
                channel.Close("Test complete", new GoodbyeDetails()
                {
                    Message = "Client #" + _id
                });
            }
        }
Exemplo n.º 22
0
 public void Start()
 {
     try {
         WampChannel = new DefaultWampChannelFactory().CreateJsonChannel(Helper.ApiUrlWssBase, "realm1");
         WampChannel.RealmProxy.Monitor.ConnectionBroken += OnConnectionBroken;
         WampChannel.RealmProxy.Monitor.ConnectionError  += OnConnectionError;
         WampChannelOpenTask = WampChannel.Open();
     }
     catch (Exception e) {
         Console.WriteLine("Live Start: " + e.Message);
         PoloniexBot.CLI.Manager.PrintError(e.Message);
     }
 }
Exemplo n.º 23
0
        public IDisposable ConnectOrderBook(PoloniexTicker ticker)
        {
            ticker.OrderBook.Updates.Clear();
            DefaultWampChannelFactory channelFactory =
                new DefaultWampChannelFactory();

            IWampChannel wampChannel = channelFactory.CreateJsonChannel(PoloniexServerAddress, "realm1");

            wampChannel.Open().Wait();

            ISubject <OrderBookUpdateInfo> subject = wampChannel.RealmProxy.Services.GetSubject <OrderBookUpdateInfo>(ticker.OrderBook.Owner.Name, new OrderBookUpdateInfoConverter());

            return(subject.Subscribe(x => ticker.OrderBook.OnRecvUpdate(x)));
        }
Exemplo n.º 24
0
        private IDisposable SubscribeToTicker()
        {
            DefaultWampChannelFactory channelFactory =
                new DefaultWampChannelFactory();

            IWampChannel wampChannel = channelFactory.CreateJsonChannel(PoloniexServerAddress, "realm1");

            wampChannel.Open().Wait();

            ISubject <PoloniexTicker> subject = wampChannel.RealmProxy.Services.GetSubject <PoloniexTicker>("ticker", new PoloniexTickerConverter());
            IDisposable disposable            = subject.Subscribe(x => GetTickerItem(x));

            return(disposable);
        }
Exemplo n.º 25
0
        public static void Main(string[] args)
        {
            DefaultWampChannelFactory factory = new DefaultWampChannelFactory();
            IWampChannel channel = factory.CreateJsonChannel(serverAddress, "realm1");

            channel.Open().Wait();

            IWampRealmProxy realmProxy = channel.RealmProxy;

            CallGetInfo(realmProxy);
            CallGetSelectedObjects(realmProxy);

            Console.ReadLine();
        }
Exemplo n.º 26
0
 public void Connect()
 {
     DefaultWampChannelFactory channelFactory = new DefaultWampChannelFactory();
     this.serverws = channelFactory.CreateChannel(Manager.wsUrl);
     try
     {
         serverws.Open();
         this.ServeurIsConnected = true;
     }
     catch (Exception e)
     {
         Console.WriteLine(e.Message);
         this.ServeurIsConnected = false;
     }
 }
Exemplo n.º 27
0
        public void Connect()
        {
            DefaultWampChannelFactory channelFactory = new DefaultWampChannelFactory();

            this.serverws = channelFactory.CreateChannel(Manager.wsUrl);
            try
            {
                serverws.Open();
                this.ServeurIsConnected = true;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                this.ServeurIsConnected = false;
            }
        }
Exemplo n.º 28
0
        public void StartClient()
        {
            DefaultWampChannelFactory factory = new DefaultWampChannelFactory();

            channel = factory.CreateJsonChannel(location, "realm1");
            channel.Open();
            IWampRealmProxy realmProxy = channel.RealmProxy;

            subscription =
                realmProxy.Services
                .GetSubject("ticker")
                .Subscribe(x =>
            {
                Console.WriteLine("Got Event: " + x);
            });
        }
Exemplo n.º 29
0
        public Client()
        {
            DefaultWampChannelFactory channelFactory = new DefaultWampChannelFactory();
            IWampChannel<JToken> channel = channelFactory.CreateChannel("ws://projetx.nordri.fr:8080/");
            channel.Open();

            // PubSub subscription:
            ISubject<CommonUserLogin> subject = channel.GetSubject<CommonUserLogin>("ws.projetx.common.user.login");
            IDisposable subscription = subject.Subscribe(x => Console.WriteLine("Received " + x));

            CommonUserLogin cul = new CommonUserLogin()
                        {
                            topic="ws.projetx",
                            data = new CommonUserLoginData() {TimeStamp=0,UserEmail="victorien.vanroye",UserId=0,Username="******"},
                        };
            Console.Write(JsonConvert.SerializeObject(cul));
        }
Exemplo n.º 30
0
        private static IDisposable ClientCode(string serverAddress)
        {
            DefaultWampChannelFactory channelFactory =
                new DefaultWampChannelFactory();

            IWampChannel wampChannel =
                channelFactory.CreateJsonChannel(serverAddress, "realm1");

            wampChannel.Open().Wait();

            ISubject <int> subject =
                wampChannel.RealmProxy.Services.GetSubject <int>("com.myapp.topic1");

            IDisposable disposable = subject.Subscribe(x => GetValue(x));

            return(disposable);
        }
Exemplo n.º 31
0
        public static void Main(string[] args)
        {
            const string serverAddress = "wss://api.poloniex.com";

            var factory = new DefaultWampChannelFactory();

            var channel = factory.CreateJsonChannel(serverAddress, "realm1");

            channel.RealmProxy.Monitor.ConnectionError += Monitor_ConnectionError;
            channel.Open().Wait(5000);

            var subscription = channel.RealmProxy.Services.GetSubject("ticker")
                               .Subscribe(x =>
            {
                Task.Run(() =>
                {
                    var t = new TickerItem(x);
                    Console.WriteLine("Got Data For: " + t.CurrencyPair);
                    // work with the data however you want
                    if (t.PercentChange > 0m)
                    {
                    }
                    if (t.PercentChange < 0m)
                    {
                        // holder for our post data
                        var postVars = new List <KeyValuePair <string, string> >();

                        // create the nonce
                        var nonce = DateTime.Now.Ticks.ToString();

                        // add our post vars
                        postVars.Add(new KeyValuePair <string, string>("nonce", nonce));
                        postVars.Add(new KeyValuePair <string, string>("command", "returnBalances"));

                        // make the actual api request
                        var res = MakeRequest(postVars);
                        Console.WriteLine($"Command: returnBalances returned | {res}");
                    }
                }).Wait(20000);
            });

            Console.WriteLine("Waiting For Data");
            Console.ReadLine();
            channel.Close();
            subscription.Dispose();
        }
        public static IObservable <IWampChannel> CreateWampChannel(string url, string realm)
        {
            return(Observable.Create <IWampChannel>(observer =>
            {
                DefaultWampChannelFactory channelFactory = new DefaultWampChannelFactory();

                IWampChannel channel = channelFactory.CreateJsonChannel(url, realm);

                var realmProxy = channel.RealmProxy;

                EventHandler <WampSessionCreatedEventArgs> onEstablished = (e, w) =>
                {
                    Trace.WriteLine($"WAMP-channel opened. SessionId: {((WampSharp.V2.Client.WampSessionClient<Newtonsoft.Json.Linq.JToken>)channel.RealmProxy.Monitor).Session}");
                    observer.OnNext(channel);
                };
                EventHandler <WampConnectionErrorEventArgs> onFail = (e, w) =>
                {
                    Trace.WriteLine($"WAMP-channel in error. SessionId: {((WampSharp.V2.Client.WampSessionClient<Newtonsoft.Json.Linq.JToken>)channel.RealmProxy.Monitor).Session}. Error: {w.Exception.Message}");
                    observer.OnError(w.Exception);
                };
                EventHandler <WampSessionCloseEventArgs> onEnd = (e, w) =>
                {
                    Trace.WriteLine($"WAMP-channel completed. SessionId: {((WampSharp.V2.Client.WampSessionClient<Newtonsoft.Json.Linq.JToken>)channel.RealmProxy.Monitor).Session}. Reason: {w.Reason}");
                    observer.OnError(new Exception(w.Reason));
                };

                realmProxy.Monitor.ConnectionEstablished += onEstablished;
                realmProxy.Monitor.ConnectionError += onFail;
                realmProxy.Monitor.ConnectionBroken += onEnd;

                Trace.WriteLine("Opening WAMP-channel");
                channel.Open().ConfigureAwait(false);

                Action onClose = () =>
                {
                    Trace.WriteLine("Disconnecting WAMP-channel");
                    channel.Close();
                    realmProxy.Monitor.ConnectionEstablished -= onEstablished;
                    realmProxy.Monitor.ConnectionError -= onFail;
                    realmProxy.Monitor.ConnectionBroken -= onEnd;
                };

                return Disposable.Create(onClose);
            }));
        }
Exemplo n.º 33
0
        public static void Main(string[] args)
        {
            DefaultWampChannelFactory factory =
                new DefaultWampChannelFactory();

            const string serverAddress = "ws://localhost:8081";

            IWampChannel channel =
                factory.CreateJsonChannel(serverAddress, "realm1");

            channel.Open().Wait(5000);

            IArgumentsService proxy =
                channel.RealmProxy.Services.GetCalleeProxy <IArgumentsService>();

            proxy.Ping();
            Console.WriteLine("Pinged!");

            int result = proxy.Add2(2, 3);

            Console.WriteLine("Add2: {0}", result);

            var starred = proxy.Stars();

            Console.WriteLine("Starred 1: {0}", starred);

            starred = proxy.Stars(nick: "Homer");
            Console.WriteLine("Starred 2: {0}", starred);

            starred = proxy.Stars(stars: 5);
            Console.WriteLine("Starred 3: {0}", starred);

            starred = proxy.Stars(nick: "Homer", stars: 5);
            Console.WriteLine("Starred 4: {0}", starred);

            string[] orders = proxy.Orders("coffee");
            Console.WriteLine("Orders 1: {0}", string.Join(", ", orders));

            orders = proxy.Orders("coffee", limit: 10);
            Console.WriteLine("Orders 2: {0}", string.Join(", ", orders));

            Console.ReadLine();
        }
Exemplo n.º 34
0
        private static async Task <IWampChannel> ConnectAsync(AppArguments appArguments)
        {
            var factory = new DefaultWampChannelFactory();
            IWampClientAuthenticator clientAuthenticator = GetClientAuthenticator(appArguments.AuthMethod, appArguments.AuthId);

            var channel = clientAuthenticator == null
                ? factory.CreateJsonChannel(GetUri(appArguments), appArguments.Realm)
                : factory.CreateJsonChannel(GetUri(appArguments), appArguments.Realm, clientAuthenticator);

            channel.RealmProxy.Monitor.ConnectionEstablished +=
                (sender, args) =>
            {
                Console.WriteLine("connected session with ID " + args.SessionId);

                dynamic details = args.WelcomeDetails.OriginalValue.Deserialize <dynamic>();

                Console.WriteLine("authenticated using method '{0}' and provider '{1}'", details.authmethod,
                                  details.authprovider);

                Console.WriteLine("authenticated with authid '{0}' and authrole '{1}'", details.authid,
                                  details.authrole);
            };

            while (!channel.RealmProxy.Monitor.IsConnected)
            {
                try
                {
                    Console.WriteLine($"Trying to connect to the server {appArguments.Uri}...");

                    channel.Open().Wait();
                }
                catch (Exception e)
                {
                    Console.WriteLine($"Failed to connect: {e.Message}");
                    Console.WriteLine("Retrying in 5 sec...");

                    await Task.Delay(TimeSpan.FromSeconds(5));
                }
            }

            return(channel);
        }
Exemplo n.º 35
0
        private async static Task Run(string wsuri, string realm)
        {
            Console.WriteLine("Connecting to {0}, realm {1}", wsuri, realm);

            DefaultWampChannelFactory factory = new DefaultWampChannelFactory();

            IWampChannel channel =
                factory.CreateJsonChannel(wsuri, realm);

            IWampClientConnectionMonitor monitor = channel.RealmProxy.Monitor;
            
            monitor.ConnectionBroken += OnClose;
            monitor.ConnectionError += OnError;

            await channel.Open().ConfigureAwait(false);

            IWampRealmServiceProvider services = channel.RealmProxy.Services;

            // SUBSCRIBE to a topic and receive events
            ISubject<string> helloSubject = 
                services.GetSubject<string>("com.example.onhello");

            IDisposable subscription =
                helloSubject.Subscribe
                    (x => Console.WriteLine("event for 'onhello' received: {0}", x));

            Console.WriteLine("subscribed to topic 'onhello'");


            // REGISTER a procedure for remote calling
            Add2Service callee = new Add2Service();

            await services.RegisterCallee(callee)
                .ConfigureAwait(false);
            
            Console.WriteLine("procedure add2() registered");


            // PUBLISH and CALL every second... forever
            ISubject<int> onCounterSubject =
                services.GetSubject<int>("com.example.oncounter");

            IMul2Service proxy =
                services.GetCalleeProxy<IMul2Service>();

            int counter = 0;

            while (true)
            {
                // PUBLISH an event
                onCounterSubject.OnNext(counter);
                Console.WriteLine("published to 'oncounter' with counter {0}", counter);
                counter++;


                // CALL a remote procedure
                try
                {
                    int result = await proxy.Multiply(counter, 3)
                        .ConfigureAwait(false);

                    Console.WriteLine("mul2() called with result: {0}", result);
                }
                catch (WampException ex)
                {
                    if (ex.ErrorUri != "wamp.error.no_such_procedure")
                    {
                        Console.WriteLine("call of mul2() failed: " + ex);
                    }
                }


                await Task.Delay(TimeSpan.FromSeconds(1))
                    .ConfigureAwait(false);
            }
        }
Exemplo n.º 36
0
        public void SubscribeAndWait(int workTimeMillis = 85)
        {
            var factory = new DefaultWampChannelFactory();
            var binding = new JTokenMsgpackBinding();

            var channel = factory.CreateChannel("realm", new WebSocket4NetBinaryConnection<JToken>(Configs.ServerAddress, binding), binding);
            try
            {
                channel.Open().Wait();
                //
                for (var i = 0; i < Configs.N_SUBJECTS; i++)
                {
                    string topicUri = Configs.SUBJECT_ + i;
                    channel.RealmProxy.Services.GetSubject<WsEvent>(topicUri).Subscribe(
                        @event =>
                        {
                            Interlocked.Add(ref EventsConsumed, 1);
                            //
                            if (@event.Id%100 == 0)
                            {
                                Logger.Info("Client #" + _id + ". Processing event #" + @event.Id);
                            }
                            //
                            Thread.Sleep(workTimeMillis);
                        },
                        ex =>
                        {
                            Logger.Error($"Error during {topicUri} subscription", ex);
                        });
                }
                //
                while (!_shouldTerminate())
                {
                    Thread.Sleep(1);
                }
            }
            catch (Exception ex)
            {
                Logger.Error("Error in Client #" + _id, ex);
                // ReSharper disable once LocalizableElement
                MessageBox.Show("Error in Client #" + _id + "\r\n\r\n" + ex, "Error");
                Application.Exit();
            }
            finally
            {
                channel.Close("Test complete", new GoodbyeDetails()
                {
                    Message = "Client #" + _id
                });
            }
        }