Пример #1
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();
            }
        }
Пример #2
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();
            }
        }
Пример #3
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();
            }
        }
Пример #4
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();
            }
        }
Пример #5
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");
        }
Пример #6
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();
            }
        }
        /// <summary>
        /// TODO: Use factories instead of using this.connnectionType.
        /// </summary>
        /// <param name="serviceDefinitionsProvider"></param>
        /// <param name="proxyDefinitionsProvider"></param>
        /// <returns></returns>
        protected (IRpcServerHost, IRpcChannel) CreateServerAndConnection(
            IRpcServiceDefinitionsProvider serviceDefinitionsProvider = null,
            Action <RpcServerOptions> configServerOptions             = null,
            Action <RpcClientOptions> configClientOptions             = null,
            Action <IServiceCollection> configureServices             = null)
        {
            var rpcServerId = RpcServerId.NewId();

            var serverOptions = new RpcServerOptions {
                Serializer = this.serializer
            };
            var clientOptions = new RpcClientOptions {
                Serializer = this.serializer
            };

            configServerOptions?.Invoke(serverOptions);
            configClientOptions?.Invoke(clientOptions);

            IServiceProvider services = GetServiceProvider(configureServices);

            switch (this.ConnectionType)
            {
            case RpcConnectionType.LightweightTcp:
            case RpcConnectionType.LightweightSslTcp:
            {
                var host = new LightweightRpcServer(rpcServerId, serviceDefinitionsProvider, services, serverOptions, this.LightweightOptions,
                                                    loggerFactory: services.GetService <ILoggerFactory>());

                SslServerOptions sslServerOptions = null;
                if (this.ConnectionType == RpcConnectionType.LightweightSslTcp)
                {
                    sslServerOptions = new SslServerOptions(new X509Certificate2(TestCertificates.ServerPFXPath, "1111"));
                }

                host.AddEndPoint(new TcpRpcEndPoint("127.0.0.1", TcpTestPort, false, sslServerOptions));

                SslClientOptions sslClientOptions = null;
                if (this.ConnectionType == RpcConnectionType.LightweightSslTcp)
                {
                    sslClientOptions = new SslClientOptions {
                        RemoteCertificateValidationCallback = this.ValidateTestCertificate
                    };
                }
                var connection = new TcpRpcConnection(
                    new RpcConnectionInfo("TCP", new Uri($"lightweight.tcp://127.0.0.1:{TcpTestPort}"), rpcServerId),
                    sslClientOptions,
                    clientOptions.AsImmutable(),
                    this.LightweightOptions);

                return(host, connection);
            }

            case RpcConnectionType.LightweightNamedPipe:
            {
                var server = new LightweightRpcServer(rpcServerId, serviceDefinitionsProvider, services, serverOptions, this.LightweightOptions,
                                                      loggerFactory: services.GetService <ILoggerFactory>());
                server.AddEndPoint(new NamedPipeRpcEndPoint("testpipe"));

                var connection = new NamedPipeRpcConnection(
                    new RpcConnectionInfo(new Uri("lightweight.pipe://./testpipe")),
                    clientOptions.AsImmutable(),
                    this.LightweightOptions);

                return(server, connection);
            }

            case RpcConnectionType.LightweightInproc:
            {
                Pipe requestPipe  = new Pipe(new PipeOptions(readerScheduler: PipeScheduler.ThreadPool));
                Pipe responsePipe = new Pipe(new PipeOptions(readerScheduler: PipeScheduler.Inline));

                var host = new LightweightRpcServer(rpcServerId, serviceDefinitionsProvider, services, serverOptions,
                                                    loggerFactory: services.GetService <ILoggerFactory>());
                host.AddEndPoint(new InprocRpcEndPoint(new DirectDuplexPipe(requestPipe.Reader, responsePipe.Writer)));

                var connection = new InprocRpcConnection(new RpcConnectionInfo("Direct", new Uri("direct:localhost"), rpcServerId),
                                                         new DirectDuplexPipe(responsePipe.Reader, requestPipe.Writer), clientOptions.AsImmutable());
                return(host, connection);
            }

            case RpcConnectionType.Grpc:
            {
                var host = new GrpcServer(rpcServerId, serviceDefinitionsProvider, services, serverOptions);
                host.AddEndPoint(GrpcCoreFullStackTestsBase.CreateEndPoint());

                var connection = new GrpcConnection(
                    new RpcConnectionInfo("TCP", new Uri($"grpc://localhost:{GrpcCoreFullStackTestsBase.GrpcTestPort}"), rpcServerId),
                    TestCertificates.GrpcSslCredentials, clientOptions.AsImmutable());
                return(host, connection);
            }

#if PLAT_NET_GRPC
            case RpcConnectionType.NetGrpc:
            {
                var server = CreateNetGrpcServer(serviceDefinitionsProvider, rpcServerId, serverOptions, configureServices);
                //var host = new GrpcServer(rpcServerId, serviceDefinitionsBuilder, null, options);
                //host.AddEndPoint(GrpcCoreFullStackTestsBase.CreateEndPoint());

                var handler = new System.Net.Http.HttpClientHandler();
                handler.ServerCertificateCustomValidationCallback =
                    (httpRequestMessage, cert, cetChain, policyErrors) =>
                {
                    return(true);
                };
                var channelOptions = new GrpcNet.Client.GrpcChannelOptions()
                {
                    HttpClient        = new System.Net.Http.HttpClient(handler),
                    DisposeHttpClient = true
                };


                var connection = new NetGrpcConnection(
                    new RpcConnectionInfo("net-grpc", new Uri($"grpc://localhost:{GrpcCoreFullStackTestsBase.GrpcTestPort}"), rpcServerId),
                    clientOptions.AsImmutable(), channelOptions);
                return(server, connection);
            }
#endif
            }

            throw new NotSupportedException();
        }