Ejemplo n.º 1
0
        public async Task SimpleObjectServiceCallTest()
        {
            var serverBuilder = new RpcServiceDefinitionsBuilder();

            serverBuilder.RegisterService <ISimpleService>();
            var host = new GrpcServer(serverBuilder, null, this.options);

            host.AddEndPoint(CreateEndPoint());

            host.Start();
            try
            {
                var serviceImpl = new TestSimpleServiceImpl();
                using (var publishScope = host.PublishInstance(serviceImpl))
                {
                    var objectId   = publishScope.Value.ObjectId;
                    var connection = this.CreateGrpcConnection();

                    var clientService = connection.GetServiceInstance <ISimpleService>(objectId);
                    int res           = await clientService.AddAsync(8, 9);

                    Assert.AreEqual(8 + 9, res);
                }
            }
            finally
            {
                await host.ShutdownAsync();
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Starts the server.
        /// </summary>
        public void Start()
        {
            GrpcServer.Start();
            var port = GrpcServer.Ports.FirstOrDefault();

            Logger.Info(LoggerMessages.ServerStartedMessage(port.Host, port.Port));
        }
Ejemplo n.º 3
0
        public async Task DeviceServiceTest()
        {
            var serverBuilder = new RpcServiceDefinitionsBuilder();

            serverBuilder.RegisterService <IThermostatService>();
            var host = new GrpcServer(serverBuilder, null, this.options);

            host.AddEndPoint(CreateEndPoint());

            host.Start();
            try
            {
                var serviceImpl = new ThermostatServiceImpl();
                using (var publishScope = host.PublishInstance(serviceImpl))
                {
                    var            objectId   = publishScope.Value.ObjectId;
                    GrpcConnection connection = this.CreateGrpcConnection();

                    var clientService = connection.GetServiceInstance <IThermostatServiceClient>(objectId);
                    var acoId         = clientService.DeviceAcoId;

                    var baseClientService = (IDeviceServiceClient)clientService;
                    var acoId2            = baseClientService.DeviceAcoId;
                    Assert.AreEqual(acoId, acoId2);
                }
            }
            finally
            {
                await host.ShutdownAsync();
            }
        }
Ejemplo n.º 4
0
        public async Task ServiceProviderServiceCallTest()
        {
            var serverBuilder = new RpcServiceDefinitionsBuilder();

            serverBuilder.RegisterService <IServiceProviderService>()
            .RegisterService <ISimpleService>();

            var host = new GrpcServer(serverBuilder, null, this.options);

            host.AddEndPoint(CreateEndPoint());

            host.Start();
            try
            {
                var serviceImpl = new ServiceProviderServiceImpl(host.ServicePublisher);

                using (var publishScope = host.PublishSingleton <IServiceProviderService>(serviceImpl))
                {
                    var connection = this.CreateGrpcConnection();

                    var clientService = connection.GetServiceSingleton <IServiceProviderServiceClient>();
                    var serviceRef    = await clientService.GetSimpleServiceAsync();

                    var simpleService = connection.GetServiceInstance(serviceRef);

                    int res = await simpleService.AddAsync(8, 9);

                    Assert.AreEqual(8 + 9, res);
                }
            }
            finally
            {
                await host.ShutdownAsync();
            }
        }
Ejemplo n.º 5
0
        public async Task EventHandlersTest()
        {
            var serverBuilder = new RpcServiceDefinitionsBuilder();

            serverBuilder.RegisterService <ISimpleServiceWithEvents>();

            var host = new GrpcServer(serverBuilder, null, this.options);

            host.AddEndPoint(CreateEndPoint());
            host.Start();

            try
            {
                var serviceImpl = new TestServiceWithEventsImpl();
                using (var publishScope = host.PublishInstance(serviceImpl))
                {
                    var objectId = publishScope.Value.ObjectId;

                    var connection = this.CreateGrpcConnection();

                    var clientService = connection.GetServiceInstance <ISimpleServiceWithEvents>(objectId);

                    TaskCompletionSource <ValueChangedEventArgs> detailedTcs     = new TaskCompletionSource <ValueChangedEventArgs>();
                    EventHandler <ValueChangedEventArgs>         detailedHandler = (s, e) =>
                    {
                        detailedTcs.SetResult(e);
                    };

                    clientService.DetailedValueChanged += detailedHandler;

                    await((IRpcProxy)clientService).WaitForPendingEventHandlersAsync();

                    clientService.SetValueAsync(12).Forget();

                    var completedTask = await Task.WhenAny(detailedTcs.Task, Task.Delay(1000));

                    Assert.AreEqual(detailedTcs.Task, completedTask);
                    Assert.IsTrue(completedTask.IsCompletedSuccessfully());

                    var detailedArgs = detailedTcs.Task.Result;

                    clientService.DetailedValueChanged -= detailedHandler;
                    await((IRpcProxy)clientService).WaitForPendingEventHandlersAsync();
                    clientService.SetValueAsync(13).Forget();

                    await Task.Delay(200);

                    Assert.IsFalse(serviceImpl.HasDetailedValueChangedHandler);
                    Assert.IsFalse(serviceImpl.HasValueChangedHandler);

                    Assert.AreEqual(12, detailedArgs.NewValue);
                    Assert.AreEqual(0, detailedArgs.OldValue);
                }
            }
            finally
            {
                await host.ShutdownAsync();
            }
        }
Ejemplo n.º 6
0
        public void Start()
        {
            ServerStarted = true;
            GrpcServer.Start();

            // Can't log before the job manager starts (Master Interpreter looks for the first newline to decide when it's safe to send commands)
            //Console.WriteLine("Listening for progress feedback on address {0}", ServerAddress);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// 启动服务
        /// </summary>
        public void Start()
        {
            GrpcServer server = new GrpcServer(_config.LocalAddress.Split(':')[0], int.Parse(_config.LocalAddress.Split(':')[1]), _config.ClusterToken, new DebugConsole());

            server.Register(typeof(IHost), typeof(Host), _host);
            server.Start().Wait();

            DebugConsole.WriteLine("Raft is Running...");
            DebugConsole.WriteLine($"NodeId:{_config.NodeId} name:{_config.NodeName} address:{_config.LocalAddress}...");
        }
Ejemplo n.º 8
0
 private static async Task Main(string[] args)
 {
     Console.Title = "gRPC Service";
     GrpcServer.Start();
     Console.WriteLine("gRPC server started.\nPress spacebar to notify item changes or any other key to stop it.");
     while (Console.ReadKey().Key == ConsoleKey.Spacebar)
     {
         RaiseItemsChanged();
     }
     await GrpcServer.Stop();
 }
Ejemplo n.º 9
0
        public static async Task Main(string[] args)
        {
            // This example shows how to explicitly setup a gRPC RPC server and a Pipelines RPC server
            // with a common service publisher.
            //
            // In a real scenario, it is probably more suitable to use the .NET generic host
            // (https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/generic-host).
            //
            // The NetGrpcServer example shows what a host setup could look like.


            Console.WriteLine("Initializing gRPC server and pipelines server.");
            var serviceCollection = new ServiceCollection();

            ConfigureServices(serviceCollection);

            var serviceProvider = serviceCollection.BuildServiceProvider();

            var definitionsBuilder = new RpcServiceDefinitionBuilder();
            var rpcPublisher       = new RpcServicePublisher(definitionsBuilder);

            RegisterServiceDefinitions(definitionsBuilder);
            PublishServices(rpcPublisher);

            var serializer = new ProtobufSerializer();

            var grpcServer = new GrpcServer(rpcPublisher, serviceProvider, serializer);

            grpcServer.AllowAutoPublish = true;
            grpcServer.AddEndPoint(CreateGrpcEndPoint(50051));

            var pipelinesServer = new RpcPipelinesServer(rpcPublisher, serviceProvider, serializer);

            pipelinesServer.AllowAutoPublish = true;
            pipelinesServer.AddEndPoint(new TcpPipelinesEndPoint("127.0.0.1", 50052, false));

            Console.WriteLine("Starting gRPC server and pipelines server.");

            // Once the gRPC server is started, it is no longer possible to register service definitions.
            grpcServer.Start();
            pipelinesServer.Start();

            Console.WriteLine("gRPC server and pipelines server are running, press any key to shutdown.");

            Console.ReadKey();

            Console.WriteLine("Shutting down servers.");

            await Task.WhenAll(grpcServer.ShutdownAsync(), pipelinesServer.ShutdownAsync());

            Console.WriteLine("Ended");
        }
Ejemplo n.º 10
0
        public Task StartAsync(CancellationToken cancellationToken)
        {
            _applicationLifetime.ApplicationStarted.Register(OnStarted);
            _applicationLifetime.ApplicationStopping.Register(OnStopping);

            GrpcEnvironment.SetLogger(new LogLevelFilterLogger(new GrpcLogger(_logger), GrpcLogLevel.Debug, false));
            _server.Start();

            string serverAddress = _server.Ports.Select(p => string.Format("{0}:{1}", p.Host, p.Port.ToString())).First();

            _logger.LogInformation($"Server running on: {serverAddress}", null);

            return(Task.CompletedTask);
        }
Ejemplo n.º 11
0
        public async Task BlockingServiceCallTest()
        {
            var serverBuilder = new RpcServiceDefinitionsBuilder();

            serverBuilder
            .RegisterService <IBlockingService>()
            .RegisterService <ISimpleService>();

            var host = new GrpcServer(serverBuilder, null, this.options);

            host.AddEndPoint(CreateEndPoint());

            host.Start();

            try
            {
                var serviceImpl = new TestBlockingSimpleServiceImpl();
                using (var publishScope = host.PublishInstance(serviceImpl))
                {
                    var objectId = publishScope.Value.ObjectId;

                    var connection = this.CreateGrpcConnection();

                    var clientService = connection.GetServiceInstance <IBlockingServiceClient>(objectId);

                    int blockingRes = clientService.Add(12, 13);
                    Assert.AreEqual(12 + 13, blockingRes);

                    int asyncRes = await clientService.AddAsync(8, 9);

                    Assert.AreEqual(8 + 9, asyncRes);

                    clientService.Value = 123.45;
                    Assert.AreEqual(123.45, await clientService.GetValueAsync());

                    await clientService.SetValueAsync(543.21);

                    Assert.AreEqual(543.21, clientService.Value);
                }
            }
            finally
            {
                await host.ShutdownAsync();
            }
        }
Ejemplo n.º 12
0
        static void Main(string[] args)
        {
            Console.WriteLine(Environment.CurrentDirectory);
            var options = new GrpcServerOptions()
            {
                Host           = "127.0.0.1",
                Port           = 3002,
                NamespaceName  = "Atlantis.Simple",
                PackageName    = "Atlantis.Simple",
                ServiceName    = "AtlantisService",
                ScanAssemblies = new string[]
                {
                    typeof(IPersonServicer).Assembly.FullName
                }
            };

            var consulSetting = new ConsulSettingOptions()
            {
                ConsulAddressUrl = "http://192.168.0.251:8500"
            };
            var serviceOptions = new ConsulServiceOptions()
            {
                ServiceName = "Atlantis.Test",
                Address     = "127.0.0.1",
                Port        = 3002,
                TTL         = 1000
            };

            var consulManager = new ConsulManager()
                                .Init(consulSetting)
                                .WithServiceOptions(serviceOptions);

            consulManager.Service.RegisteAsync().Wait();

            //GrpcConfiguration.LoggerFactory=new Loggerfac();

            var server = new GrpcServer(options);

            ObjectContainer.Register <IPersonServicer, PersonServicer>(LifeScope.Single);
            server.Start();

            Console.WriteLine("Server is running...");
            Console.ReadLine();
        }
Ejemplo n.º 13
0
        static void Main(string[] args)
        {
            var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());

            XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));

            TripRepository    tripRepository    = new TripRepository();
            TripValidator     tripValidator     = new TripValidator();
            AccountRepository accountRepository = new AccountRepository();
            AccountValidator  accountValidator  = new AccountValidator();
            BookingRepository bookingRepository = new BookingRepository();
            BookingValidator  bookingValidator  = new BookingValidator();
            ITripServices     tripServices      = new TripServicesImpl(accountRepository, tripRepository, bookingRepository,
                                                                       accountValidator, tripValidator, bookingValidator);

            TripServicesGrpcImpl tripServicesGrpc = new TripServicesGrpcImpl(tripServices);
            GrpcServer           server           = new GrpcServer(int.Parse(ConfigurationManager.AppSettings["port"]),
                                                                   ConfigurationManager.AppSettings["host"], tripServicesGrpc);

            server.Start();
        }
Ejemplo n.º 14
0
        internal static GrpcServer StartGrpcServer(int port, bool isRetryEnabled)
        {
            // max 3 times attemps, including the original request.
            RetryPolicy retryPolicy = isRetryEnabled ?
                                      new RetryPolicy(3, (float)0.1, 5, 2) :
                                      null;

            GrpcServerLegacyQueryHandlerBase mockLegacyQueryHandler = new RetryableLegacyQueryHandler();
            //GrpcServerLegacyQueryHandlerBase mockLegacyQueryHandler =
            //                                    isRetryEnabled ?
            //                                        (GrpcServerLegacyQueryHandlerBase)new MockRetryableLegacyQueryHandler() :
            //                                        (GrpcServerLegacyQueryHandlerBase)new MockLegacyQueryHandler();
            LegacyQueryService legacyQueryService = GrpcServer.CreateLegacyQueryService(mockLegacyQueryHandler);

            GrpcServer grpcServer = new GrpcServer(
                port, legacyQueryService, retryPolicy: retryPolicy);

            grpcServer.Start();

            return(grpcServer);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// </summary>
        static void Init()
        {
            Console.WriteLine($"Init() called on thread {Thread.CurrentThread.ManagedThreadId}");

            MqttTransportSettings mqttSetting = new MqttTransportSettings(TransportType.Mqtt_Tcp_Only)
            {
                RemoteCertificateValidationCallback =
                    (sender, certificate, chain, sslPolicyErrors) => true
            };

            ITransportSettings[] settings = { mqttSetting };

            // Open a connection to the Edge runtime
            var mcTask = ModuleClient.CreateFromEnvironmentAsync(settings);

            mcTask.Wait();
            s_moduleClient = mcTask.Result;
            s_moduleClient.OpenAsync().Wait();

            // Get module twin for initial settings
            Task <Twin> twinTask = s_moduleClient.GetTwinAsync();

            twinTask.Wait();
            Twin twin = twinTask.Result;

            OnDesiredPropertiesUpdate(twin.Properties.Desired, s_moduleClient).Wait();
            s_moduleClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertiesUpdate, null);

            s_grpcServer = new GrpcServer("VideoProcessorModule", OnImageReceived);
            Console.WriteLine("Starting gRPC server");
            s_grpcServer.Start();

            Task processingTask = new Task(ProcessingLoop);

            processingTask.Start();

            Console.WriteLine("IoT Hub module client initialized.");
        }