예제 #1
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();
        }
예제 #2
0
        private void StartWampRouter()
        {
            _host = new WampAuthenticationHost(new UserNameBasedAuthenticationFactory());

            string routeUrl = $"{UrlUtils.AdminFolderName}/{WampConsoleUrl}";

            if (routeUrl.StartsWith("/"))
            {
                routeUrl = routeUrl.Substring(1);
            }

            _host.RegisterTransport(
                new AspNetWebSocketTransport(routeUrl, new UserNameBasedCookieAuthenticationFactory()),
                new JTokenJsonBinding(new JsonSerializer
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            }));

            IWampHostedRealm realm = _host.RealmContainer.GetRealmByName(DefaultRealmName);

            realm.SessionCreated += SessionCreated;
            realm.SessionClosed  += SessionRemoved;
            _host.Open();

            FixWampRoute(routeUrl);
        }
예제 #3
0
        static void Main(string[] args)
        {
            Console.WriteLine("Infra.CNC.Simulator 1.0");

            const string location = "ws://127.0.0.1:4099/";

            var simulator = new Simulator();


            using (IWampHost host = new WampHost())
            {
                var jsonSerializer = JsonSerializer.Create();

                jsonSerializer.ContractResolver = new CamelCasePropertyNamesContractResolver();

                IWampBinding jsonBinding = new JTokenJsonBinding(jsonSerializer);

                host.RegisterTransport(new FleckWebSocketTransport(location), jsonBinding);

                IWampHostedRealm realm = host.RealmContainer.GetRealmByName("infra.cncService.simulator");

                // Host WAMP application components

                host.Open();

                Console.WriteLine("Server is running on " + location);

                realm.Services.RegisterCallee(new ServerInformationService()).Wait();

                Console.WriteLine("Registered server information service");

                Console.WriteLine("Press any key to send CNC data (x to exit)");



                var choise = Console.ReadKey().KeyChar;

                var subject = realm.Services.GetSubject <ISimulatorValue>("cncData");

                while (choise != 'x' && choise != 'X')
                {
                    simulator.GenerateValues();

                    subject.OnNext(simulator.Root);

                    Console.WriteLine("Data was sent!");

                    choise = Console.ReadKey().KeyChar;
                }

                Console.WriteLine(Environment.NewLine + "Goodbye");

                Console.ReadLine();
            }
        }
예제 #4
0
        public void Start()
        {
            _router = new WampHost();
            var jsonBinding = new JTokenJsonBinding();
            var msgPack     = new JTokenMsgpackBinding();

            _router.RegisterTransport(new FleckWebSocketTransport("ws://0.0.0.0:8080/ws"), jsonBinding, msgPack);
            _router.Open();

            var realm = _router.RealmContainer.GetRealmByName("com.weareadaptive.reactivetrader");

            realm.HostMetaApiService();
        }
예제 #5
0
        private static IDisposable StartServer()
        {
            var host = new WampHost();

            host.RegisterTransport(new VtortolaWebSocketTransport(new IPEndPoint(IPAddress.Loopback, 8080), true),
                                   new JTokenJsonBinding(), new JTokenMsgpackBinding(), new ProtobufBinding());

            host.Open();

            var realm = host.RealmContainer.GetRealmByName("realm1");

            realm.Services.RegisterCallee(new SumService(), new CalleeNameInterceptor()).Wait();             // add services (aka, RPC endpoints) like this
            // realm.Services.RegisterPublisher // register some event triggerer here

            return(host);
        }
예제 #6
0
        private void StartWampRouter()
        {
            _host = new WampAuthenticationHost(new UserNameBasedAuthenticationFactory());

            _host.RegisterTransport(new AspNetWebSocketTransport("Composite/api/Router"
                                                                 , new UserNameBasedCookieAuthenticationFactory()),
                                    new JTokenJsonBinding(new JsonSerializer()
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            }));

            IWampHostedRealm realm = _host.RealmContainer.GetRealmByName(DefaultRealmName);

            realm.SessionCreated += SessionCreated;
            realm.SessionClosed  += SessionRemoved;
            _host.Open();
        }
예제 #7
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            WampHost host = new WampHost();

            app.Map("/ws", builder =>
            {
                builder.UseWebSockets();

                host.RegisterTransport(new AspNetCoreWebSocketTransport(builder),
                                       new JTokenJsonBinding());
            });

            host.Open();
        }
예제 #8
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseFileServer();

            WampHost host = new WampHost();

            app.Map("/chat", builder =>
            {
                builder.UseWebSockets(new WebSocketOptions());

                host.RegisterTransport(new AspNetCoreWebSocketTransport(builder),
                                       new JTokenJsonBinding());
            });

            host.Open();
        }
예제 #9
0
        private static IDisposable StartNetMQServer()
        {
            var host = new WampHost();

            var serverContext   = NetMQContext.Create();
            var serverSocket    = serverContext.CreateResponseSocket();         // serverContext.CreateRouterSocket();
            var serverPoller    = new Poller(serverSocket);
            var serverScheduler = new NetMQScheduler(serverContext, serverPoller);

            serverPoller.PollTillCancelledNonBlocking();

            host.RegisterTransport(new NetMQTransport(serverSocket, serverScheduler),
                                   new JTokenJsonBinding(), new JTokenMsgpackBinding(), new ProtobufBinding());

            host.Open();

            var realm = host.RealmContainer.GetRealmByName("realm1");

            realm.Services.RegisterCallee(new SumService(), new CalleeNameInterceptor()).Wait();             // add services (aka, RPC endpoints) like this
            // realm.Services.RegisterPublisher // register some event triggerer here

            return(host);
        }
예제 #10
0
        /// <summary>
        ///     Configure the application pipeline.
        /// </summary>
        /// <param name="app">
        ///     The application pipeline builder.
        /// </param>
        /// <param name="loggerFactory">
        ///     The logger factory.
        /// </param>
        public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(LogLevel.Trace,
                                     includeScopes: true
                                     );

            app.UseDeveloperExceptionPage();

            WampHost wampHost = new WampHost();

            app.Map("/ws", ws =>
            {
                ws.UseWebSockets(new WebSocketOptions
                {
                    ReplaceFeature = true
                });

                wampHost.RegisterTransport(
                    new AspNetCoreWebSocketTransport(ws),
                    new JTokenJsonBinding(),
                    new JTokenMsgpackBinding()
                    );
            });
            wampHost.Open();

            ILogger realm1Logger = app.ApplicationServices
                                   .GetRequiredService <ILoggerFactory>()
                                   .CreateLogger("WAMP_REALM1");

            IWampHostedRealm realm1 = wampHost.RealmContainer.GetRealmByName("realm1");

            realm1.SessionCreated += (s, args) =>
            {
                realm1Logger.LogInformation("Session {SessionId} created.",
                                            args.SessionId
                                            );
            };
            realm1.SessionClosed += (s, args) =>
            {
                realm1Logger.LogInformation("Session {SessionId} closed.",
                                            args.SessionId
                                            );
            };

            ILogger realm2Logger = app.ApplicationServices
                                   .GetRequiredService <ILoggerFactory>()
                                   .CreateLogger("WAMP_REALM2");

            IWampHostedRealm realm2 = wampHost.RealmContainer.GetRealmByName("realm2");

            realm2.SessionCreated += (s, args) =>
            {
                realm2Logger.LogInformation("Session {SessionId} created.",
                                            args.SessionId
                                            );
            };
            realm2.SessionClosed += (s, args) =>
            {
                realm2Logger.LogInformation("Session {SessionId} closed.",
                                            args.SessionId
                                            );
            };
        }
예제 #11
0
        private Server()
        {
            _wampHost = new WampHost();

            _wampHost.RegisterTransport(new FleckWebSocketTransport(Configs.ServerAddress),
                                        new JTokenMsgpackBinding());
            //_wampHost.RegisterTransport(new VtortolaWebSocketTransport(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2015), true),
            //    new JTokenMsgpackBinding());
            //
            _wampHost.Open();
            //
            _realm = _wampHost.RealmContainer.GetRealmByName("realm");
            _realm.SessionCreated +=
                (sender, args) =>
            {
                Interlocked.Increment(ref CurrentSessions);
                Logger.Info(sender + " session created: " + args.SessionId + " details=" + args.HelloDetails);
            };
            _realm.SessionClosed +=
                (sender, args) =>
            {
                Interlocked.Decrement(ref CurrentSessions);
                Logger.Info(sender + " session closed : " + args.SessionId + " reason=" + args.Reason +
                            " closeType=" + args.CloseType);
            };
            _realm.TopicContainer.TopicCreated +=
                (sender, args) =>
            {
                _topics.TryAdd(args.Topic.TopicUri, new TopicView(args.Topic));
                Logger.Info(sender + " topic created: " + args.Topic.TopicUri);
            };
            _realm.TopicContainer.TopicRemoved +=
                (sender, args) =>
            {
                TopicView t;
                _topics.TryRemove(args.Topic.TopicUri, out t);
                Logger.Info(sender + " topic removed: " + t);
            };
            _realm.TopicContainer.Topics.ForEach(t => _topics.TryAdd(t.TopicUri, new TopicView(t)));
            //
            Observable.Timer(TimeSpan.FromSeconds(0), TimeSpan.FromSeconds(1 /*intervalSeconds*/)).Subscribe(l =>
            {
                var ticks = Rate; // produce 1000 events each second
                for (var t = 0; t <= ticks / 10; ++t)
                {
                    Parallel.For(t * 10, (t + 1) * 10, i =>
                    {
                        var random   = new Random((int)(DateTime.Now.Ticks + i));
                        var topicUri = string.Intern(Configs.SUBJECT_ + random.Next(0, Configs.N_SUBJECTS));
                        TopicView topicView;
                        if (_topics.TryGetValue(topicUri, out topicView))
                        {
                            var wsEvent = new WsEvent(Math.Round(random.NextDouble() * 100000) / 100000.0);
                            topicView.Publish(wsEvent);
                            NumPublished = wsEvent.Id;
                            if (wsEvent.Id % 10000 == 0)
                            {
                                Logger.Info("Published " + wsEvent.Id + " events");
                            }
                        }
                    });
                }
            });
        }
예제 #12
0
        public async Task ExecuteAsync(IConsole console)
        {
            WampHost wampHost = new WampHost();

            JTokenJsonBinding        jsonBinding        = new JTokenJsonBinding();
            JTokenCborBinding        cborBinding        = new JTokenCborBinding();
            JTokenMessagePackBinding messagePackBinding = new JTokenMessagePackBinding();

            IWebHost host =
                WebHost.CreateDefaultBuilder()
                .UseKestrel(options =>
            {
                options.Listen(IPAddress.Loopback, Port,
                               builder =>
                {
                    // Log all of the http bytes as they are sent and received
                    builder.UseConnectionLogging();

                    // Configure RawSocket transport
                    wampHost
                    .RegisterTransport(new AspNetCoreRawSocketTransport(builder),
                                       jsonBinding,
                                       cborBinding,
                                       messagePackBinding);
                });
            })
                .Configure(app =>
            {
                app.Map("/ws",
                        builder =>
                {
                    builder.UseWebSockets();

                    // Configure WebSockets transport
                    wampHost
                    .RegisterTransport(new AspNetCoreWebSocketTransport(builder, null),
                                       jsonBinding,
                                       cborBinding,
                                       messagePackBinding);
                });

                app.UseStaticFiles(new StaticFileOptions
                {
                    FileProvider =
                        new
                        PhysicalFileProvider(Path
                                             .Combine(Directory.GetCurrentDirectory(),
                                                      "static")),
                    RequestPath = ""
                });

                app.UseDirectoryBrowser(new DirectoryBrowserOptions
                {
                    FileProvider =
                        new
                        PhysicalFileProvider(Path
                                             .Combine(Directory.GetCurrentDirectory(),
                                                      "static")),
                    RequestPath = ""
                });

                wampHost.Open();
            })
                .Build();

            await host.RunAsync().ConfigureAwait(false);
        }
예제 #13
0
		private static IDisposable StartNetMQServer()
		{
			var host = new WampHost();

			var serverContext = NetMQContext.Create();
			var serverSocket = serverContext.CreateResponseSocket();// serverContext.CreateRouterSocket();
			var serverPoller = new Poller(serverSocket);
			var serverScheduler = new NetMQScheduler(serverContext, serverPoller);
			serverPoller.PollTillCancelledNonBlocking();

			host.RegisterTransport(new NetMQTransport(serverSocket, serverScheduler),
				new JTokenJsonBinding(), new JTokenMsgpackBinding(), new ProtobufBinding());

			host.Open();

			var realm = host.RealmContainer.GetRealmByName("realm1");
			realm.Services.RegisterCallee(new SumService(), new CalleeNameInterceptor()).Wait(); // add services (aka, RPC endpoints) like this
			// realm.Services.RegisterPublisher // register some event triggerer here

			return host;
		}
예제 #14
0
		private static IDisposable StartServer()
		{
			var host = new WampHost();
			host.RegisterTransport(new VtortolaWebSocketTransport(new IPEndPoint(IPAddress.Loopback, 8080), true),
				new JTokenJsonBinding(), new JTokenMsgpackBinding(), new ProtobufBinding());

			host.Open();

			var realm = host.RealmContainer.GetRealmByName("realm1");
			realm.Services.RegisterCallee(new SumService(), new CalleeNameInterceptor()).Wait(); // add services (aka, RPC endpoints) like this
			// realm.Services.RegisterPublisher // register some event triggerer here

			return host;
		}