Example #1
0
        static async Task Main(string[] args)
        {
            string url   = "ws://127.0.0.1:8080/ws/";
            string realm = "realm1";

            WampChannelFactory channelFactory = new WampChannelFactory();

            IWampChannel channel =
                channelFactory.ConnectToRealm(realm)
                .WebSocketTransport(new Uri(url))
                .JsonSerialization()
                .Build();

            // Fire this code when the connection establishes
            channel.RealmProxy.Monitor.ConnectionEstablished += (sender, e) =>
            {
                Console.WriteLine("Session open! :" + e.SessionId);
            };

            // Fire this code when the connection has broken
            channel.RealmProxy.Monitor.ConnectionBroken += (sender, e) =>
            {
                Console.WriteLine("Session closed! :" + e.Reason);
            };

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

            // Your code goes here: use WAMP via the channel variable to
            // call, register, subscribe and publish ..

            await Task.Delay(1000);
        }
Example #2
0
        public BrokerConnection(string uri, string realm)
        {
            var channel = new WampChannelFactory()
                          .ConnectToRealm(realm)
                          .WebSocketTransport(new Uri(uri))
                          .JsonSerialization()
                          .Build();

            async Task Connect()
            {
                Log.Information("Trying to connect to broker {brokerUri}", uri);

                try
                {
                    await channel.Open();

                    Log.Debug("Connection Opened.");

                    _subject.OnNext(Connected.Yes(new Broker(channel)));
                }
                catch (Exception exception)
                {
                    Log.Error(exception, "Connection Failed.");

                    _subject.OnNext(Connected.No <IBroker>());
                    throw;
                }
            }

            _reconnector = new WampChannelReconnector(channel, Connect);
        }
Example #3
0
        public async Task InMemoryTest()
        {
            var transport = new InMemoryTransport(Scheduler.Default);
            var binding   = new JTokenJsonBinding();
            var realm     = "some.realm";

            var router = new WampHost();

            router.RegisterTransport(transport, new[] { binding });
            router.Open();

            var calleeConnection       = transport.CreateClientConnection(binding, Scheduler.Default);
            WampChannelFactory factory = new WampChannelFactory();

            var callee = factory.CreateChannel(realm, calleeConnection, binding);
            await callee.Open();

            await callee.RealmProxy.Services.RegisterCallee(new WampTest());


            var callerConnection = transport.CreateClientConnection(binding, Scheduler.Default);
            var caller           = factory.CreateChannel(realm, callerConnection, binding);
            await caller.Open();

            var proxy  = caller.RealmProxy.Services.GetCalleeProxy <IWampTest>();
            var result = await proxy.Echo("1");

            Assert.That(result, Is.EqualTo("1"));

            await caller.Close(WampErrors.CloseNormal, new GoodbyeDetails());

            await callee.Close(WampErrors.CloseNormal, new GoodbyeDetails());

            router.Dispose();
        }
Example #4
0
		public void BenchmarkMessages()
		{

			var host = StartServer();
			var factory = new WampChannelFactory();

			var channel = factory.ConnectToRealm("realm1")
				.WebSocketTransport("ws://127.0.0.1:8080/")
				//.MsgpackSerialization(new JsonSerializer { TypeNameHandling = TypeNameHandling.Auto })
				//.JsonSerialization(new JsonSerializer { TypeNameHandling = TypeNameHandling.Auto })
				.JsonSerialization()
				//.CraAuthentication(authenticationId: "peter", secret: "secret1")
				.Build();

			channel.RealmProxy.Monitor.ConnectionEstablished += (sender, eventArgs) => _testOutputHelper.WriteLine("Connected with ID " + eventArgs.SessionId);

			channel.Open().Wait();
				
			var proxy = channel.RealmProxy.Services.GetCalleeProxy<ISumService>(new CallerNameInterceptor());

			const int randCnt = 100;
			var rand = new Random(42);
			var randoms = new int[randCnt];
			for (int i = 0; i < randCnt; i++) randoms[i] = rand.Next(10000000, 20000000);
			var package = new SumPackage { Numbers = randoms };

			var sw = new Stopwatch();
			long timeFromClient = 0, timeToClient = 0;
			const int cnt = 1000;
			for (int j = 0; j < cnt; j++)
			{
				sw.Start();
				var sum = proxy.SumPackage(package).Result;
				sw.Stop();
				Assert.Equal(randoms.Sum(), sum);
				for (int i = 0; i < randCnt; i++) randoms[i] = rand.Next(10000000, 20000000);
				var times = proxy.TimeDiff(Stopwatch.GetTimestamp()).Result;
				timeFromClient += times.Item1;
				timeToClient += Stopwatch.GetTimestamp() - times.Item2;
			}

			_testOutputHelper.WriteLine("Completed {0} sum passes in {1}ms", cnt, sw.ElapsedMilliseconds);
			_testOutputHelper.WriteLine("Client to server latency: {0}us", timeFromClient / cnt / 10);
			_testOutputHelper.WriteLine("Server to client latency: {0}us", timeToClient / cnt / 10);

			sw.Reset();
			var tree = new SumServiceTree();
			SumServiceTree.FillTree(tree, rand, 2);
			_testOutputHelper.WriteLine("Starting large message transfer.");
			sw.Start();
			var result = proxy.Increment(tree).Result;
			sw.Stop();
			Assert.Equal(tree.Leaf + 1, result.Leaf);
			_testOutputHelper.WriteLine("Completed large transfer in {0}ms", sw.Elapsed.TotalMilliseconds);

			channel.Close();
			host.Dispose();
		}
Example #5
0
        public void Start()
        {
            WampChannelFactory channelFactory = new WampChannelFactory();

            WampChannel = channelFactory.ConnectToRealm("realm1")
                          .WebSocketTransport(new Uri(Helper.ApiUrlWssBase))
                          .JsonSerialization()
                          .Build();

            WampChannel.RealmProxy.Monitor.ConnectionBroken += OnConnectionBroken;

            WampChannelOpenTask = WampChannel.Open();
        }
Example #6
0
        public void OpenAsyncWillNotBlockOnConnectionLost()
        {
            var wampChannelFactory           = new WampChannelFactory <MockRaw>(mFormatter);
            var mockConnection               = new MockConnection <MockRaw>(mFormatter);
            var mockControlledWampConnection = mockConnection.SideAToSideB;

            var wampChannel = wampChannelFactory.CreateChannel(mockControlledWampConnection);
            var openAsync   = wampChannel.OpenAsync();

            Assert.IsFalse(openAsync.IsCompleted);
            mockConnection.SideBToSideA.Dispose();
            Assert.IsTrue(openAsync.IsCompleted);
        }
Example #7
0
        public void OpenAsyncWillThrowAndExpcetionIfAnErrorOccurs()
        {
            var wampChannelFactory = new WampChannelFactory <MockRaw>(mFormatter);
            var mockConnection     = new MockConnection <MockRaw>(mFormatter);

            var wampChannel   = wampChannelFactory.CreateChannel(mockConnection.SideAToSideB);
            var openAsyncTask = wampChannel.OpenAsync();

            Exception myException = new Exception("My exception");

            mockConnection.SideBToSideA.SendError(myException);

            Assert.IsNotNull(openAsyncTask.Exception);

            Assert.That(openAsyncTask.Exception.InnerException, Is.EqualTo(myException));
        }
        public PcaWampClient(Uri address, string realm, IWampClientAuthenticator authenticator, TypeMapper typeMapper)
        {
            var serializer = new Newtonsoft.Json.JsonSerializer();

            if (typeMapper != null)
            {
                serializer.Converters.Add(new DerivedEntityJsonConverter(typeMapper));
            }

            var builder =
                new WampChannelFactory().ConnectToRealm(realm)
                .WebSocketTransport(address)
                .JsonSerialization(serializer);

            this.channel = authenticator != null?
                           builder.Authenticator(authenticator).Build() :
                               builder.Build();
        }
Example #9
0
        static async Task StartWamp()
        {
            WampChannelFactory cf = new WampChannelFactory();

            IWampChannel channel =
                cf.ConnectToRealm("jdm")
//                       .WebSocketTransport("ws://40.86.85.83:8080/ws")
                .WebSocketTransport("ws://ws01.jdm1.maassluis:9001/wamp")
                .JsonSerialization()
                //.Authenticator(new TicketAuthenticator())
                .Build();
            var mon = channel.RealmProxy.Monitor;

            mon.ConnectionEstablished += (p1, p2) => Console.WriteLine("Established");
            mon.ConnectionError       += (p1, p2) => Console.WriteLine("Error");
            mon.ConnectionBroken      += (p1, p2) => Console.WriteLine("Broken");
            Console.WriteLine("Connecting...");
            await channel.Open();

            Console.WriteLine("Connected");

            IWhisper instance = new Whisper();

            IWampRealmProxy realm = channel.RealmProxy;

            registration = await realm.Services.RegisterCallee(instance);

            Console.WriteLine("RPC registered");
            ISubject <string> newWhisper = realm.Services.GetSubject <string>("nl.jdm.newWhisper");

            newWhisperSubscription =
                newWhisper.Subscribe(name => Console.WriteLine($"New whisper detected: {name}"));

            Action registerWhisper = () =>
            {
                Console.WriteLine("Registering whisper...");
                newWhisper.OnNext("johan");
            };

            registerWhisper();

            discoverSubscription = realm.Services.GetSubject <string>("nl.jdm.discover")
                                   .Subscribe(_ => registerWhisper());
        }
 /// <summary>
 /// Installs the WAMP-communication stack
 /// </summary>
 /// <param name="services"></param>
 /// <returns></returns>
 public static IServiceCollection AddWamp(this IServiceCollection services)
 {
     services
     .AddSingleton(provider =>
     {
         var settings = provider.GetService <IOptions <WampSettings> >();
         var factory  = new DefaultWampChannelFactory();
         var channel  = factory.CreateJsonChannel(settings.Value.Router, settings.Value.Realm);
         return(channel);
     })
     .AddSingleton(provider =>
     {
         var settings          = provider.GetService <IOptions <WampSettings> >();
         var channelObservable = WampChannelFactory.CreateWampChannel(settings.Value.Router, settings.Value.Realm);
         return(channelObservable.Retry().Replay(1).RefCount());
     })
     .AddTransient <IWampOperation, WampOperation>()
     .AddSingleton <IWampService, WampService>();
     return(services);
 }
Example #11
0
        static void Main(string[] args)
        {
            var apiKey = "PUT_YOUR_API_KEY_HERE";

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            WampChannelFactory factory =
                new WampChannelFactory();

            const string serverAddress = "wss://live.prohashing.com:443/ws";

            IWampClientAuthenticator myAuthenticator = new WampCraClientAuthenticator(authenticationId: "web", secret: "web");

            IWampChannel channel =
                factory.ConnectToRealm("mining")
                .WebSocketTransport(serverAddress)
                .SetSecurityOptions(o =>
            {
                o.EnabledSslProtocols = SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12;
                //o.Certificates.Add(new X509Certificate2(@"server_cert.pem"));
                o.AllowNameMismatchCertificate = true;
                o.AllowUnstrustedCertificate   = true;
            })
                .JsonSerialization()
                .Authenticator(myAuthenticator)
                .Build();

            ServicePointManager.ServerCertificateValidationCallback = (s, crt, chain, policy) => true;

            channel.Open().Wait(5000);

            Console.WriteLine("Connection Complete ");

            //IWampRealmProxy realmProxy = channel.RealmProxy;   //use this for a subscription in conjunction with commented out below
            IArgumentsService proxy = channel.RealmProxy.Services.GetCalleeProxy <IArgumentsService>();

            Console.WriteLine("Channel Proxy: " + channel.RealmProxy.Name);

            JObject myResults = proxy.f_all_balance_updates(apiKey);
            var     path      = Directory.GetCurrentDirectory();

            path += "\\UserBalance.json";
            File.WriteAllText(path, myResults.ToString());


            myResults = proxy.f_all_profitability_updates();
            path      = Directory.GetCurrentDirectory();
            path     += "\\Profitability.json";
            File.WriteAllText(path, myResults.ToString());


            var myResults2 = proxy.f_all_miner_updates(apiKey);


            path  = Directory.GetCurrentDirectory();
            path += "\\SessionDetails.json";
            File.WriteAllText(path, myResults2.ToString());

            //----------------------------------------
            //int received = 0;
            //IDisposable subscription = null;



            //subscription =
            //    realmProxy.Services.GetSubject("balance_updates_"+apiKey)
            //        .Subscribe(x =>
            //        {
            //            Console.WriteLine("Got Event: " + x);

            //            received++;

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

            //Console.ReadLine();
            ////----------------------------------------
        }
Example #12
0
        public void BenchmarkMessages()
        {
            var host    = StartServer();
            var factory = new WampChannelFactory();

            var channel = factory.ConnectToRealm("realm1")
                          .WebSocketTransport("ws://127.0.0.1:8080/")
                          //.MsgpackSerialization(new JsonSerializer { TypeNameHandling = TypeNameHandling.Auto })
                          //.JsonSerialization(new JsonSerializer { TypeNameHandling = TypeNameHandling.Auto })
                          .JsonSerialization()
                          //.CraAuthentication(authenticationId: "peter", secret: "secret1")
                          .Build();

            channel.RealmProxy.Monitor.ConnectionEstablished += (sender, eventArgs) => _testOutputHelper.WriteLine("Connected with ID " + eventArgs.SessionId);

            channel.Open().Wait();

            var proxy = channel.RealmProxy.Services.GetCalleeProxy <ISumService>(new CallerNameInterceptor());

            const int randCnt = 100;
            var       rand    = new Random(42);
            var       randoms = new int[randCnt];

            for (int i = 0; i < randCnt; i++)
            {
                randoms[i] = rand.Next(10000000, 20000000);
            }
            var package = new SumPackage {
                Numbers = randoms
            };

            var       sw = new Stopwatch();
            long      timeFromClient = 0, timeToClient = 0;
            const int cnt = 1000;

            for (int j = 0; j < cnt; j++)
            {
                sw.Start();
                var sum = proxy.SumPackage(package).Result;
                sw.Stop();
                Assert.Equal(randoms.Sum(), sum);
                for (int i = 0; i < randCnt; i++)
                {
                    randoms[i] = rand.Next(10000000, 20000000);
                }
                var times = proxy.TimeDiff(Stopwatch.GetTimestamp()).Result;
                timeFromClient += times.Item1;
                timeToClient   += Stopwatch.GetTimestamp() - times.Item2;
            }

            _testOutputHelper.WriteLine("Completed {0} sum passes in {1}ms", cnt, sw.ElapsedMilliseconds);
            _testOutputHelper.WriteLine("Client to server latency: {0}us", timeFromClient / cnt / 10);
            _testOutputHelper.WriteLine("Server to client latency: {0}us", timeToClient / cnt / 10);

            sw.Reset();
            var tree = new SumServiceTree();

            SumServiceTree.FillTree(tree, rand, 2);
            _testOutputHelper.WriteLine("Starting large message transfer.");
            sw.Start();
            var result = proxy.Increment(tree).Result;

            sw.Stop();
            Assert.Equal(tree.Leaf + 1, result.Leaf);
            _testOutputHelper.WriteLine("Completed large transfer in {0}ms", sw.Elapsed.TotalMilliseconds);

            channel.Close();
            host.Dispose();
        }
Example #13
0
        public void BenchmarkMessagesProtobuf()
        {
            var host       = StartServer();
            var factory    = new WampChannelFactory();
            var binding    = new ProtobufBinding();
            var connection = new WebSocket4NetBinaryConnection <ProtobufToken>("ws://localhost:8080/", binding);
            var channel    = factory.CreateChannel("realm1", connection, binding);

            channel.RealmProxy.Monitor.ConnectionEstablished += (sender, eventArgs) => _testOutputHelper.WriteLine("Connected with ID " + eventArgs.SessionId);

            channel.Open().Wait();

            var proxy = channel.RealmProxy.Services.GetCalleeProxy <ISumService>(new CallerNameInterceptor());

            const int randCnt = 100;
            var       rand    = new Random(42);
            var       randoms = new int[randCnt];

            for (int i = 0; i < randCnt; i++)
            {
                randoms[i] = rand.Next(10000000, 20000000);
            }
            var package = new SumPackage {
                Numbers = randoms
            };

            var       sw = new Stopwatch();
            long      timeFromClient = 0, timeToClient = 0;
            const int cnt = 1000;

            for (int j = 0; j < cnt; j++)
            {
                sw.Start();
                var sum = proxy.SumPackage(package).Result;
                sw.Stop();
                Assert.Equal(randoms.Sum(), sum);
                for (int i = 0; i < randCnt; i++)
                {
                    randoms[i] = rand.Next(10000000, 20000000);
                }
                var times = proxy.TimeDiff(Stopwatch.GetTimestamp()).Result;
                timeFromClient += times.Item1;
                timeToClient   += Stopwatch.GetTimestamp() - times.Item2;
            }

            _testOutputHelper.WriteLine("Completed {0} sum passes in {1}ms", cnt, sw.ElapsedMilliseconds);
            _testOutputHelper.WriteLine("Client to server latency: {0}us", timeFromClient / cnt / 10);
            _testOutputHelper.WriteLine("Server to client latency: {0}us", timeToClient / cnt / 10);

            sw.Reset();
            var tree = new SumServiceTree();

            SumServiceTree.FillTree(tree, rand, 2);
            _testOutputHelper.WriteLine("Starting large message transfer.");
            sw.Start();
            var result = proxy.Increment(tree).Result;

            sw.Stop();
            Assert.True(tree.IsExactMatch(result, 1));
            _testOutputHelper.WriteLine("Completed large transfer in {0}ms", sw.Elapsed.TotalMilliseconds);

            channel.Close();
            host.Dispose();
        }
Example #14
0
        private async static Task Run(string wsuri, string realm)
        {
            Console.WriteLine("Connecting to {0}, realm {1}", wsuri, realm);

            WampChannelFactory factory = new WampChannelFactory();

            IWampChannel channel =
                factory.ConnectToRealm(realm)
                .WebSocketTransport(wsuri)
                .JsonSerialization()
                .Build();

            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
            HelloSubscriber subscriber = new HelloSubscriber();

            IAsyncDisposable subscriptionDisposable =
                await services.RegisterSubscriber(subscriber)
                .ConfigureAwait(false);

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

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

            IAsyncDisposable registrationDisposable =
                await services.RegisterCallee(callee)
                .ConfigureAwait(false);

            Console.WriteLine("procedure add2() registered");


            // PUBLISH and CALL every second... forever
            CounterPublisher publisher =
                new CounterPublisher();

            IDisposable publisherDisposable =
                channel.RealmProxy.Services.RegisterPublisher(publisher);

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

            int counter = 0;

            while (true)
            {
                // PUBLISH an event
                publisher.Publish(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);
            }
        }
        async private void StreamBtn_Click(object sender, EventArgs e)
        {
            if (!IsStreamingToWAMP)
            {
                //maybe check if the connection before start wamp
                string CrossbarAddress = CrossbarIPTextBox.Text + "/ws";
                string CrossbarRealm   = RealmTextbox.Text;

                //This was the old code, might have to do some kind of hybrid depending on the url written.

                /*DefaultWampChannelFactory channelFactory = new DefaultWampChannelFactory();
                 * IWampChannel channel = channelFactory.CreateJsonChannel("wss://syn.ife.no/crossbarproxy/ws", CrossbarRealm); //CrossbarAddress
                 *
                 * channel.Open().Wait();
                 * //Task openTask = channel.Open()
                 * //openTask.Wait(5000);*/

                //if (CrossbarAddress.Contains("wss://")){
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                //}

                WampChannelFactory factory = new WampChannelFactory();

                IWampChannel channel = factory.ConnectToRealm(CrossbarRealm)
                                       .WebSocketTransport(new Uri(CrossbarAddress + "/ws"))
                                       .JsonSerialization()
                                       .Build();

                IWampRealmProxy realmProxy = channel.RealmProxy;

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

                    dynamic details = arg.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);
                };

                channel.RealmProxy.Monitor.ConnectionBroken +=
                    (sender_inner, arg) =>
                {
                    dynamic details = arg.Details.OriginalValue.Deserialize <dynamic>();
                    Console.WriteLine("disconnected " + arg.Reason + " " + details.reason + details);
                    Console.WriteLine("disconnected " + arg.Reason);
                };

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

                WAMPSubject = realmProxy.Services.GetSubject("RETDataSample");

                SelectedTracker.GazeDataReceived += HandleGazeData;
                IsStreamingToWAMP = true;
                WAMPThread        = new Thread(() => {
                    while (IsStreamingToWAMP)
                    {
                        try
                        {
                            while (GazeEventQueue.Any())
                            {
                                GazeDataEventArgs gazeEvent;
                                GazeEventQueue.TryDequeue(out gazeEvent);
                                float gazeX = 0;
                                float gazeY = 0;
                                if (gazeEvent.LeftEye.GazePoint.Validity == Validity.Valid &&
                                    gazeEvent.RightEye.GazePoint.Validity == Validity.Valid)
                                {
                                    gazeX = (gazeEvent.LeftEye.GazePoint.PositionOnDisplayArea.X + gazeEvent.RightEye.GazePoint.PositionOnDisplayArea.X) / 2;
                                    gazeY = (gazeEvent.LeftEye.GazePoint.PositionOnDisplayArea.Y + gazeEvent.RightEye.GazePoint.PositionOnDisplayArea.Y) / 2;
                                }
                                else if (gazeEvent.LeftEye.GazePoint.Validity == Validity.Valid)
                                {
                                    gazeX = gazeEvent.LeftEye.GazePoint.PositionOnDisplayArea.X;
                                    gazeY = gazeEvent.LeftEye.GazePoint.PositionOnDisplayArea.Y;
                                }
                                else if (gazeEvent.RightEye.GazePoint.Validity == Validity.Valid)
                                {
                                    gazeX = gazeEvent.RightEye.GazePoint.PositionOnDisplayArea.X;
                                    gazeY = gazeEvent.RightEye.GazePoint.PositionOnDisplayArea.Y;
                                }

                                if (gazeEvent.LeftEye.Pupil.PupilDiameter != -1 || gazeEvent.RightEye.Pupil.PupilDiameter != -1)
                                {
                                    CurrentPupilDiameters[0] = Double.IsNaN(gazeEvent.LeftEye.Pupil.PupilDiameter) ? -1 : gazeEvent.LeftEye.Pupil.PupilDiameter;
                                    CurrentPupilDiameters[1] = Double.IsNaN(gazeEvent.RightEye.Pupil.PupilDiameter) ? -1 : gazeEvent.RightEye.Pupil.PupilDiameter;
                                }

                                WampEvent evt = new WampEvent();
                                evt.Arguments = new object[] { SelectedTracker.SerialNumber,
                                                               new object[] { CurrentPupilDiameters[0],
                                                                              gazeEvent.LeftEye.GazePoint.PositionOnDisplayArea.X,
                                                                              gazeEvent.LeftEye.GazePoint.PositionOnDisplayArea.Y,
                                                                              CurrentPupilDiameters[1],
                                                                              gazeEvent.RightEye.GazePoint.PositionOnDisplayArea.X,
                                                                              gazeEvent.RightEye.GazePoint.PositionOnDisplayArea.Y,
                                                                              gazeEvent.LeftEye.GazeOrigin.PositionInUserCoordinates.X,
                                                                              gazeEvent.LeftEye.GazeOrigin.PositionInUserCoordinates.Y,
                                                                              gazeEvent.LeftEye.GazeOrigin.PositionInUserCoordinates.Z,
                                                                              gazeEvent.RightEye.GazeOrigin.PositionInUserCoordinates.X,
                                                                              gazeEvent.RightEye.GazeOrigin.PositionInUserCoordinates.Y,
                                                                              gazeEvent.RightEye.GazeOrigin.PositionInUserCoordinates.Z,
                                                                              gazeX, gazeY } };
                                WAMPSubject.OnNext(evt);
                            }
                        }
                        catch (Exception exp)
                        {
                            //do nothing, skip
                            Console.Write(exp);
                        }
                    }
                });
                WAMPThread.Start();

                if (StreamBtn.InvokeRequired)
                {
                    StreamBtn.BeginInvoke((MethodInvoker) delegate() { this.StreamBtn.Text = "Stop"; });
                }
                else
                {
                    StreamBtn.Text = "Stop";
                }
            }
            else
            {
                IsStreamingToWAMP = false;
                SelectedTracker.GazeDataReceived -= HandleGazeData;
                if (StreamBtn.InvokeRequired)
                {
                    StreamBtn.BeginInvoke((MethodInvoker) delegate() { this.StreamBtn.Text = "Stream"; });
                }
                else
                {
                    StreamBtn.Text = "Stream";
                }
                WAMPThread.Join();
            }
        }
Example #16
0
		public void BenchmarkMessagesProtobuf()
		{
			var host = StartServer();
			var factory = new WampChannelFactory();
			var binding = new ProtobufBinding();
			var connection = new WebSocket4NetBinaryConnection<ProtobufToken>("ws://localhost:8080/", binding);
			var channel = factory.CreateChannel("realm1", connection, binding);

			channel.RealmProxy.Monitor.ConnectionEstablished += (sender, eventArgs) => _testOutputHelper.WriteLine("Connected with ID " + eventArgs.SessionId);

			channel.Open().Wait();

			var proxy = channel.RealmProxy.Services.GetCalleeProxy<ISumService>(new CallerNameInterceptor());

			const int randCnt = 100;
			var rand = new Random(42);
			var randoms = new int[randCnt];
			for (int i = 0; i < randCnt; i++) randoms[i] = rand.Next(10000000, 20000000);
			var package = new SumPackage { Numbers = randoms };

			var sw = new Stopwatch();
			long timeFromClient = 0, timeToClient = 0;
			const int cnt = 1000;
			for (int j = 0; j < cnt; j++)
			{
				sw.Start();
				var sum = proxy.SumPackage(package).Result;
				sw.Stop();
				Assert.Equal(randoms.Sum(), sum);
				for (int i = 0; i < randCnt; i++) randoms[i] = rand.Next(10000000, 20000000);
				var times = proxy.TimeDiff(Stopwatch.GetTimestamp()).Result;
				timeFromClient += times.Item1;
				timeToClient += Stopwatch.GetTimestamp() - times.Item2;
			}

			_testOutputHelper.WriteLine("Completed {0} sum passes in {1}ms", cnt, sw.ElapsedMilliseconds);
			_testOutputHelper.WriteLine("Client to server latency: {0}us", timeFromClient / cnt / 10);
			_testOutputHelper.WriteLine("Server to client latency: {0}us", timeToClient / cnt / 10);

			sw.Reset();
			var tree = new SumServiceTree();
			SumServiceTree.FillTree(tree, rand, 2);
			_testOutputHelper.WriteLine("Starting large message transfer.");
			sw.Start();
			var result = proxy.Increment(tree).Result;
			sw.Stop();
			Assert.True(tree.IsExactMatch(result, 1));
			_testOutputHelper.WriteLine("Completed large transfer in {0}ms", sw.Elapsed.TotalMilliseconds);

			channel.Close();
			host.Dispose();
		}