コード例 #1
1
        public void Init()
        {
            var serverCredentials = new SslServerCredentials(new[] { new KeyCertificatePair(File.ReadAllText(TestCredentials.ServerCertChainPath), File.ReadAllText(TestCredentials.ServerPrivateKeyPath)) });
            server = new Server
            {
                Services = { TestService.BindService(new TestServiceImpl()) },
                Ports = { { Host, ServerPort.PickUnused, serverCredentials } }
            };
            server.Start();

            var options = new List<ChannelOption>
            {
                new ChannelOption(ChannelOptions.SslTargetNameOverride, TestCredentials.DefaultHostOverride)
            };

            var asyncAuthInterceptor = new AsyncAuthInterceptor(async (authUri, metadata) =>
            {
                await Task.Delay(100);  // make sure the operation is asynchronous.
                metadata.Add("authorization", "SECRET_TOKEN");
            });

            var clientCredentials = ChannelCredentials.Create(
                new SslCredentials(File.ReadAllText(TestCredentials.ClientCertAuthorityPath)),
                new MetadataCredentials(asyncAuthInterceptor));
            channel = new Channel(Host, server.Ports.Single().BoundPort, clientCredentials, options);
            client = TestService.NewClient(channel);
        }
コード例 #2
0
ファイル: Program.cs プロジェクト: mleenhardt/grpc-playground
        static void Main(string[] args)
        {
            const int port = 1337;

            var serviceImpl = new PlaygroundServiceImpl(new PersonRepository());
            var server = new Grpc.Core.Server
            {
                Services = { PlaygroundService.BindService(serviceImpl) },
                Ports =
                {
                    new ServerPort("0.0.0.0", port, new SslServerCredentials(
                        new[]
                        {
                            new KeyCertificatePair(
                                File.ReadAllText("certificates\\server.crt"),
                                File.ReadAllText("certificates\\server.key"))
                        }))
                }
            };
            server.Start();

            Console.WriteLine("RPC server listening on port " + port);
            Console.WriteLine("Press any key to stop the server...");
            Console.ReadKey();

            serviceImpl.Shutdown();
            server.ShutdownAsync().Wait();
        }
コード例 #3
0
        public void Start()
        {
            var connectionSettings = ConnectionSettings.Create()
                                     .UseCustomLogger(new EventStoreLog4Net())
                                     .KeepReconnecting();

            if (!string.IsNullOrEmpty(EventStoreGossipSeedEndpoints))
            {
                var clusterSettings = ClusterSettings.Create()
                                      .DiscoverClusterViaGossipSeeds()
                                      .SetGossipSeedEndPoints(EventStoreGossipSeedEndpoints.Split(',').Select(x =>
                {
                    var parts = x.Split(':');
                    return(new IPEndPoint(IPAddress.Parse(parts[0]), Convert.ToInt32(parts[1])));
                }).ToArray());
                _eventStoreConnection = EventStoreConnection.Create(connectionSettings, clusterSettings);
            }
            else
            {
                _eventStoreConnection = EventStoreConnection.Create(connectionSettings, new Uri(EventStoreUri));
            }
            _eventStoreConnection.ConnectAsync().Wait();

            GrpcEnvironment.SetLogger(new GrpcLog4Net("GRPC"));
            _server = new Grpc.Core.Server
            {
                Services = { EventStore.BindService(new EventStoreImpl(_eventStoreConnection)) },
                Ports    = { new ServerPort(RpcHost, Convert.ToInt32(RpcPort), ServerCredentials.Insecure) }
            };

            _server.Start();
        }
コード例 #4
0
        static void Main(string[] args)
        {
            GrpcEnvironment.SetLogger(new Grpc.Core.Logging.ConsoleLogger());

            var type = ServiceGenerator.GenerateService(typeof(MyFirstServiceBase), typeof(InternalServiceRealization));

            MessagePack.MessagePackSerializer.SetDefaultResolver(MessagePack.Resolvers.TypelessContractlessStandardResolver.Instance);
            // setup MagicOnion and option.
            var service = MagicOnionEngine.BuildServerServiceDefinition(new[] { type },
                                                                        new MagicOnionOptions(true)
            {
                FormatterResolver = MessagePack.Resolvers.TypelessContractlessStandardResolver.Instance
            });

            var server = new Grpc.Core.Server
            {
                Services = { service },
                Ports    = { new ServerPort("localhost", 12345, ServerCredentials.Insecure) }
            };

            // launch gRPC Server.
            server.Start();

            Console.WriteLine("Started");
            // and wait.
            Console.ReadLine();
        }
コード例 #5
0
        static async Task Main(string[] args)
        {
            var server = new G.Server
            {
                Services = { Generated.SampleService.BindService(new SampleServiceImplementation()) },
                Ports    = { new G.ServerPort("127.0.0.1", 5000, G.ServerCredentials.Insecure) }
            };

            server.Start();

            var t = Task.Run(async() =>
            {
                try
                {
                    await Task.Delay(1000);
                    var client = GrpcClientFactory.Create <Service.ISampleService>(new GrpcClientOptions {
                        Url = "127.0.0.1", Port = 5000
                    }, new ProtoBufSerializer());
                    var request = new Service.SampleRequest {
                        Value = 1
                    };
                    var response = await client.SendAsync(request, CancellationToken.None);
                    Console.WriteLine("{0} -> {1}", request.Value, response.Value);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
            });

            await t;
            await server.ShutdownAsync();
        }
コード例 #6
0
        public gRPCServer(string host, int port, params ServerServiceDefinition[] serverServices)
        {
            Host           = host;
            Port           = port;
            serverInstance = new Grpc.Core.Server
//            (
//                // channel 設定請自行依專案狀況調整
//                new List<ChannelOption>
//                {
//                    new ChannelOption("grpc.keepalive_permit_without_calls", 1),
//                    new ChannelOption("grpc.http2.max_pings_without_data", 0)
//                }
//            )
            {
                Ports =
                {
                    new ServerPort(Host, Port, ServerCredentials.Insecure)
                }
            };
            foreach (var serverService in serverServices)
            {
                serverInstance.Services.Add(serverService);
            }

            serverInstance.Start();
        }
コード例 #7
0
        static async Task Main(string[] _)
        {
            //gRPCサーバーのAddress・Port設定
            var serverPort = new ServerPort("localhost", 1234, ServerCredentials.Insecure);

            //ロガーとかの設定
            var magicOnionOptions = new MagicOnionOptions(isReturnExceptionStackTraceInErrorDetail: true)
            {
                //todo:settings
            };

            //サービスクラスの実装が別アセンブリの場合はアセンブリを指定する
            var searchAssembly = new[] { typeof(Sample.MagicOnion.Server.Calculator).Assembly };

            //MagicOnion.Hostingを使用する場合
            {
                await MagicOnionHost.CreateDefaultBuilder()
                .UseMagicOnion(searchAssembly, magicOnionOptions, serverPort)
                .RunConsoleAsync();
            }

            //自前でgRPC.Core.Serverを実行する場合
            {
                var server = new Grpc.Core.Server()
                {
                    Ports    = { serverPort },
                    Services = { MagicOnionEngine.BuildServerServiceDefinition(searchAssembly, magicOnionOptions) }
                };

                server.Start();

                Console.ReadLine();
            }
        }
コード例 #8
0
        public GRPCServerBuilder Build(GRPCServerOptions options)
        {
            if (options.IsNull())
            {
                throw new MicroAngels.Core.AngleExceptions("GRPC Server Options can't be null");
            }
            if (options.Host.IsNullOrEmpty())
            {
                throw new MicroAngels.Core.AngleExceptions("GRPC Server host is required");
            }
            if (options.Port <= 0)
            {
                throw new MicroAngels.Core.AngleExceptions("GRPC Server port is required");
            }

            MagicOnionServiceDefinition service = MagicOnionEngine.BuildServerServiceDefinition(new MagicOnionOptions
            {
                MagicOnionLogger = new MagicOnionLogToGrpcLogger()
            });

            var server = new Grpc.Core.Server
            {
                Services = { service },
                Ports    = { new ServerPort(
                                 options.Host,
                                 options.Port,
                                 ServerCredentials.Insecure
                                 ) }
            };

            server.Start();

            return(this);
        }
コード例 #9
0
        private static void Start(List <ServerServiceDefinition> services, List <ChannelOption> channelOptions, Action <Exception> whenException, ServerInstance serverInstance)
        {
            try
            {
                server = new Grpc.Core.Server(channelOptions)
                {
                    Ports = { new ServerPort(serverInstance.DnsEndPoint.Host, serverInstance.DnsEndPoint.Port, ServerCredentials.Insecure) }
                };
                foreach (var service in services)
                {
                    //if (interceptors?.Count > 0)
                    //    server.Services.Add(service.Intercept(interceptors.ToArray()));
                    //else
                    server.Services.Add(service);
                }
                server.Start();


                #region 注册
                serverRegister = new ServerRegister(serverInstance.ConsulRegisterConfig.RegisterPath);
                serverRegister.Register(serverInstance, sId => serviceId = sId);
                #endregion
            }
            catch (Exception e)
            {
                Stop(whenException);
                whenException.Invoke(e);
            }
        }
コード例 #10
0
        public void GameLibrarygRpcServerTests()
        {
            Assert.IsTrue(true);

            try
            {
                GameLibraryAgent.Startup(ConnectionString);

                var gameLibraryServer = new Grpc.Core.Server
                {
                    Services = { Gamelibrary.GameLibrary.BindService(new GameLibraryServer()) },
                    Ports    = { new ServerPort(GrpcHostName, GrpcPort, ServerCredentials.Insecure) }
                };

                gameLibraryServer.Start();

                Assert.IsTrue(true);

                gameLibraryServer.ShutdownAsync().Wait();
            }

            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);

                Assert.IsTrue(false);
            }
        }
コード例 #11
0
        static void Main(string[] args)
        {
            Grpc.Core.Server server = null;

            try
            {
                server = new Grpc.Core.Server()
                {
                    Services = { GreetingService.BindService(new GreetingServiceImpl()) },
                    Ports    = { new ServerPort("localhost", Port, ServerCredentials.Insecure) }
                };
                server.Start();
                Console.WriteLine(($"The Server is listening on port : {Port}"));
                Console.ReadKey();
            }
            catch (IOException e)
            {
                Console.WriteLine($"The server failed to start: {e.Message}");
                throw;
            }
            finally
            {
                server?.ShutdownAsync().Wait();

                //if (server != null)
                //    server.ShutdownAsync().Wait();
            }
        }
コード例 #12
0
ファイル: Program.cs プロジェクト: jerryiswinwin/testGrpc
        static void Main(string[] args)
        {
            var host = "127.0.0.1";
            var port = 9999;

            var serverInstance = new Grpc.Core.Server
            {
                Ports =
                {
                    new ServerPort(host, port, ServerCredentials.Insecure)
                }
            };

            Console.WriteLine($"Demo server listening on host:{host} and port:{port}");

            serverInstance.Services.Add(
                Message.DemoService.BindService(
                    new DemoServiceImpl()));

            serverInstance.Start();

            Console.ReadKey();

            serverInstance.ShutdownAsync().Wait();
        }
コード例 #13
0
        public static async Task Main(string[] args)
        {
            var ip   = UtilsLibrary.NetworkUtils.GetMyIp();
            int port = int.Parse(ConfigurationManager.AppSettings.Get("port"));

            var reflectionServiceImpl = new ReflectionServiceImpl(ServersListMaker.Descriptor, ServerReflection.Descriptor);

            Grpc.Core.Server server = new Grpc.Core.Server
            {
                Services =
                {
                    ServersListMaker.BindService(new ServersListMakerService()),                     //для сервиса устанвливаем обработчик
                    ServerReflection.BindService(reflectionServiceImpl)
                },
                Ports = { new ServerPort(ip.ToString(), port, ServerCredentials.Insecure) }
            };
            server.Start();

            Console.WriteLine($"Сервер запущен по адресу {ip}:{port}");
            Console.WriteLine("Нажмите любую клавишу для выхода");
            Console.ReadKey();
            Console.WriteLine("Сервер завершает работу");
            await server.ShutdownAsync();

            Console.WriteLine("Сервер закрыт");
            Console.ReadKey();
        }
コード例 #14
0
        static void Main(string[] args)
        {
            const int _port = 50055;

            Grpc.Core.Server server = null;
            try
            {
                server = new Grpc.Core.Server()
                {
                    Services = { AverageService.BindService(new AverageServiceImpl()) },
                    Ports    = { new Grpc.Core.ServerPort("localhost", _port, ServerCredentials.Insecure) }
                };
                server.Start();
                Console.WriteLine(($"The Server is listening on port : {_port}"));
                Console.ReadKey();
            }
            catch (IOException e)
            {
                Console.WriteLine($"Server Connection Error: {e.Message}");
            }
            finally
            {
                server?.ShutdownAsync().Wait();
            }
        }
コード例 #15
0
        static void Main()
        {
            // Enable Support For Unencrypted HTTP2
            AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
            ParseArgs();
            var hp = Lib.ParseURL(URL);

            Grpc.Core.Server server = new Grpc.Core.Server {
                Services =
                {
                    PupSyncServices.BindService(new PupSyncServicesImpl())
                },
                Ports = { new ServerPort(hp[0], Convert.ToInt16(hp[1]), ServerCredentials.Insecure) }
            };
            server.Start();

            try {
                exec.Run();
            } catch (Exception e) when(e is OverflowException || e is FormatException)
            {
                Lib.Exit("Invalid Argument!");
            } catch (ClientException e) {
                Lib.Exit(e.Message);
            }
            Lib.Block(URL);
        }
コード例 #16
0
ファイル: Program.cs プロジェクト: KingKnecht/gRPC-PubSub
        static void Main(string[] args)
        {
            const int port      = 50052;
            var       pubsubImp = new PubSubImpl();

            Grpc.Core.Server server = new Grpc.Core.Server
            {
                Services = { PubSub.BindService(pubsubImp) },
                Ports    = { new ServerPort("localhost", port, ServerCredentials.Insecure) }
            };

            server.Start();

            Console.WriteLine("RouteGuide server listening on port " + port);
            Console.WriteLine("Insert event. 'q' to quit.");
            string input;

            while ((input = Console.ReadLine()) != "q")
            {
                pubsubImp.Publish(input);
            }

            Console.WriteLine("Press any key to stop the server...");
            Console.ReadKey();

            server.ShutdownAsync().Wait();
        }
コード例 #17
0
        static void Main(string[] args)
        {
            //gRPCサーバーのAddress・Port設定
            var serverPort = new ServerPort("localhost", 1234, ServerCredentials.Insecure);

            //ロガーとかの設定
            var magicOnionOptions = new MagicOnionOptions(isReturnExceptionStackTraceInErrorDetail: true)
            {
                //todo:settings
            };

            //サービスクラスの実装が別アセンブリの場合はアセンブリを指定する
            var searchAssembly = new[] { typeof(Sample.MagicOnion.Server.Calculator).Assembly };


            var server = new Grpc.Core.Server()
            {
                Ports    = { serverPort },
                Services =
                {
                    //MagicOnionサービス
                    MagicOnionEngine.BuildServerServiceDefinition(searchAssembly,                             magicOnionOptions),

                    //PureGrpcサービス
                    PureGrpc.Definitions.Calculator.BindService(new Sample.PureGrpc.Server.CalculatorImpl()),
                    PureGrpc.Definitions.Health.BindService(new Sample.PureGrpc.Server.HealthImpl()),
                }
            };

            server.Start();

            Console.ReadLine();
        }
コード例 #18
0
ファイル: Program.cs プロジェクト: adamaclp92/Cardealer
        static void Main(string[] args)
        {
            Grpc.Core.Server server = null;


            try
            {
                server = new Grpc.Core.Server()
                {
                    Services = { CarDealing.BindService(new CarDealerService()) },
                    Ports    = { new ServerPort("localhost", Port, ServerCredentials.Insecure) }
                };

                server.Start();

                Console.WriteLine("The server is listening on the port: " + Port);
                Console.ReadKey();
            }
            catch (IOException e)
            {
                Console.WriteLine("The server failed to start:" + e.Message);
            }
            finally
            {
                if (server != null)
                {
                    server.ShutdownAsync().Wait();
                }
            }
        }
コード例 #19
0
        private static void RunAsServer(string[] args)
        {
            try
            {
                ReadPort(args);
                ShowAppHeader(args, true);

                var server = new Grpc.Core.Server
                {
                    Services = { AccountService.BindService(new AccountsImpl()) },
                    Ports    = { new ServerPort(NetworkUtils.GetLocalIPAddress(), PORT, ServerCredentials.Insecure) }
                };



                server.Start();
                Console.ReadLine();

                Console.WriteLine("Terminating...");
                server.ShutdownAsync().Wait();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Exception encountered: {ex}");
                Console.ReadKey(intercept: true);
            }
        }
コード例 #20
0
 static void Main(string[] args)
 {
     Grpc.Core.Server server = null;
     try
     {
         server = new Grpc.Core.Server()
         {
             //Services = {SqrtService.BindService(new SqrtServiceImpl())},
             Services = { GreetingService.BindService(new GreetingServiceImpl()) },
             //Services = {CalcService.BindService(new CalculatorServiceImpl())},
             Ports = { new ServerPort("localhost", port, ServerCredentials.Insecure) }
         };
         server.Start();
         Console.WriteLine("Server is listening on port: " + port);
         Console.ReadKey();
     }
     catch (IOException ex)
     {
         Console.WriteLine("server did not start on port: " + port);
         throw;
     }
     finally
     {
         if (server != null)
         {
             server.ShutdownAsync().Wait();
         }
     }
 }
コード例 #21
0
ファイル: Program.cs プロジェクト: DropletProject/Droplet
        public static void Main(string[] args)
        {
            Console.WriteLine("Press ENTER port");
            var    portStr     = Console.ReadLine();
            var    port        = int.Parse(portStr);
            string serviceHost = GetIpAddress("192.168");

            var services = new ServiceCollection();

            services.AddConsulDiscovery(consulAddress);

            var provider         = services.BuildServiceProvider();
            var serviceRegistrar = provider.GetService <IServiceRegistrar>();
            var server           = new Grpc.Core.Server
            {
                Services = { Greeter.BindService(new GreeterImpl()) },
                Ports    = { new ServerPort(serviceHost, port, ServerCredentials.Insecure) }
            };

            server.Start();
            var info = serviceRegistrar.RegisterServiceAsync(Greeter.Descriptor.FullName, "v1.0", serviceHost, port).Result;

            Console.WriteLine($"{info.Name} service listening on port {info.Port}");
            Console.WriteLine("Press ENTER to exit");
            Console.ReadLine();

            server.ShutdownAsync().Wait();
        }
コード例 #22
0
ファイル: Program.cs プロジェクト: seayxu/gRpcChat
        static void Main(string[] args)
        {
            Console.WriteLine("Hello gRpc Chat Server!");

            //Chat.BindService(new ChatServer());
            Grpc.Core.Server server = new Grpc.Core.Server()
            {
                Services = { Chat.BindService(new ChatServer()) },
                Ports    = { new ServerPort("127.0.0.1", 4001, ServerCredentials.Insecure) }
            };

            server.Start();
            string message = null;

            do
            {
                message = Console.ReadLine();
                //if (string.IsNullOrWhiteSpace(message)) continue;

                //client.Send(new SendMessageRequest() { Name = name, Message = message });

                //Console.WriteLine($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")} \r\n Me:{listen.ResponseStream.Current.Message}");
            } while (message != "q");

            Console.ReadLine();
        }
コード例 #23
0
 public void Init()
 {
     var marshaller = new Marshaller<string>(
         (str) =>
         {
             if (str == "UNSERIALIZABLE_VALUE")
             {
                 // Google.Protobuf throws exception inherited from IOException
                 throw new IOException("Error serializing the message.");
             }
             return System.Text.Encoding.UTF8.GetBytes(str); 
         },
         (payload) =>
         {
             var s = System.Text.Encoding.UTF8.GetString(payload);
             if (s == "UNPARSEABLE_VALUE")
             {
                 // Google.Protobuf throws exception inherited from IOException
                 throw new IOException("Error parsing the message.");
             }
             return s;
         });
     helper = new MockServiceHelper(Host, marshaller);
     server = helper.GetServer();
     server.Start();
     channel = helper.GetChannel();
 }
コード例 #24
0
        private static async Task RunAsync()
        {
            var server = new Grpc.Core.Server
            {
                Ports    = { { "127.0.0.1", 5000, ServerCredentials.Insecure } },
                Services =
                {
                    ServerServiceDefinition.CreateBuilder()
                    .AddMethod(Descriptors.Method, async(requestStream, responseStream, context) =>
                    {
                        await requestStream.ForEachAsync(async request =>
                        {
                            // handle incoming request
                            // push response into stream
                            await responseStream.WriteAsync(new Message()
                            {
                                Text = request.Text
                            });
                        });
                    })
                    .Build()
                }
            };

            server.Start();

            Console.WriteLine($"Server started under [127.0.0.1:5000]. Press Enter to stop it...");
            Console.ReadLine();

            await server.ShutdownAsync();
        }
コード例 #25
0
ファイル: Program.cs プロジェクト: shibayan/ImoutoDesktop
    static async Task Main()
    {
        var port      = 1024;
        var ipAddress = (await Dns.GetHostAddressesAsync(Dns.GetHostName())).First(x => x.AddressFamily == AddressFamily.InterNetwork);

        RemoteServiceImpl serviceImpl;

        if (Environment.OSVersion.Platform == PlatformID.Win32NT)
        {
            serviceImpl = new WindowsRemoteServiceImpl();
        }
        else
        {
            serviceImpl = new UnixRemoteServiceImpl();
        }

        var server = new Grpc.Core.Server
        {
            Services = { Remoting.RemoteService.BindService(serviceImpl) },
            Ports    = { new ServerPort("0.0.0.0", port, ServerCredentials.Insecure) }
        };

        server.Start();

        Console.WriteLine($"Started - {ipAddress}:{port}");
        Console.ReadKey();

        await server.ShutdownAsync();
    }
コード例 #26
0
ファイル: BaseServer.cs プロジェクト: RodrasSilva/DIDA-GSTORE
        public void Run()
        {
            Console.Title = "Server: " + _serverId;
            Console.WriteLine("Running base version");
            var freezeUtilities       = new FreezeUtilities();
            var serverParameters      = UrlParameters.From(_serverUrl);
            var serverService         = new ServerService(_storage, freezeUtilities, _serverUrl, DelayMessage);
            var nodeService           = new NodeService(freezeUtilities, DelayMessage, RegisterServers, RegisterPartitions);
            var registerSlavesService = new SlaveRegisteringService(_storage);

            AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
            var server = new Grpc.Core.Server {
                Services =
                {
                    DIDAService.BindService(serverService),
                    NodeControlService.BindService(nodeService),
                    RegisterSlaveToMasterService.BindService(registerSlavesService),
                    BaseSlaveService.BindService(new BaseSlaveServerService(_storage))
                },
                Ports =
                {
                    new ServerPort(serverParameters.Hostname,
                                   serverParameters.Port, ServerCredentials.Insecure)
                }
            };

            server.Start();
            Console.WriteLine("Server " + _serverId + " listening on port " + serverParameters.Port);
            ReadCommands();

            server.ShutdownAsync().Wait();
        }
コード例 #27
0
        private static async Task Main(string[] args)
        {
            SetLogger(new ConsoleLogger());

            var service = new CacheServiceImpl(Logger);
            var server  = new Grpc.Core.Server
            {
                Ports    = { { "localhost", 5000, Credentials.CreateSslServerCredentials() } },
                Services =
                {
                    CacheService.BindService(service)
                    .Intercept(new CorrelationIdInterceptor())
                    .Intercept(new JwtValidationInterceptor(Logger))
                    .Intercept(new LoggingInterceptor(Logger)),

                    ServerServiceDefinition.CreateBuilder()
                    .AddMethod(Descriptors.GetAsJsonMethod, service.GetAsJson)
                    .AddMethod(Descriptors.SetAsJsonMethod, service.SetAsJson)
                    .Build()
                    .Intercept(new CorrelationIdInterceptor())
                    .Intercept(new JwtValidationInterceptor(Logger))
                    .Intercept(new LoggingInterceptor(Logger))
                }
            };

            server.Start();

            var webHost = new WebHostBuilder()
                          .UseKestrel()
                          .UseStartup <Startup>()
                          .UseUrls("http://localhost:60000")
                          .Build();

            await webHost.RunAsync();
        }
コード例 #28
0
        public static void Start(IConfigurationRoot config)
        {
            var builder = new ContainerBuilder();

            builder.RegisterInstance(config).As <IConfigurationRoot>();
            //builder.RegisterInstance(new DataContext(config)).As<IDataContext>();
            //builder.RegisterAssemblyTypes(typeof(IDataContext).GetTypeInfo().Assembly).Where(t => t.Name.EndsWith("Repository")).AsImplementedInterfaces();

            _container = builder.Build();
            var servercert     = File.ReadAllText(@"server.crt");
            var serverkey      = File.ReadAllText(@"server.key");
            var keypair        = new KeyCertificatePair(servercert, serverkey);
            var sslCredentials = new SslServerCredentials(new List <KeyCertificatePair>()
            {
                keypair
            });
            var healthService = new HealthServiceImpl();

            _server = new Grpc.Core.Server
            {
                Services = { MsgService.BindService(new MsgServiceImpl()), Grpc.Health.V1.Health.BindService(healthService) },
                Ports    = { new ServerPort("0.0.0.0", 9007, sslCredentials) }
            };
            _server.Start();
            healthService.SetStatus("Demo", Grpc.Health.V1.HealthCheckResponse.Types.ServingStatus.Serving);
            _server.ShutdownTask.Wait();
        }
コード例 #29
0
        static void Main(string[] args)
        {
            const int port = 1337;

            var serviceImpl = new PlaygroundServiceImpl(new PersonRepository());
            var server      = new Grpc.Core.Server
            {
                Services = { PlaygroundService.BindService(serviceImpl) },
                Ports    =
                {
                    new ServerPort("0.0.0.0",                             port, new SslServerCredentials(
                                       new[]
                    {
                        new KeyCertificatePair(
                            File.ReadAllText("certificates\\server.crt"),
                            File.ReadAllText("certificates\\server.key"))
                    }))
                }
            };

            server.Start();

            Console.WriteLine("RPC server listening on port " + port);
            Console.WriteLine("Press any key to stop the server...");
            Console.ReadKey();

            serviceImpl.Shutdown();
            server.ShutdownAsync().Wait();
        }
コード例 #30
0
ファイル: ShutdownTest.cs プロジェクト: larsonmpdx/grpc
 public void Init()
 {
     helper = new MockServiceHelper(Host);
     server = helper.GetServer();
     server.Start();
     channel = helper.GetChannel();
 }
コード例 #31
0
ファイル: SslCredentialsTest.cs プロジェクト: rwightman/grpc
        public void Init()
        {
            var rootCert = File.ReadAllText(TestCredentials.ClientCertAuthorityPath);
            var keyCertPair = new KeyCertificatePair(
                File.ReadAllText(TestCredentials.ServerCertChainPath),
                File.ReadAllText(TestCredentials.ServerPrivateKeyPath));

            var serverCredentials = new SslServerCredentials(new[] { keyCertPair }, rootCert, true);
            var clientCredentials = new SslCredentials(rootCert, keyCertPair);

            server = new Server
            {
                Services = { TestService.BindService(new TestServiceImpl()) },
                Ports = { { Host, ServerPort.PickUnused, serverCredentials } }
            };
            server.Start();

            var options = new List<ChannelOption>
            {
                new ChannelOption(ChannelOptions.SslTargetNameOverride, TestCredentials.DefaultHostOverride)
            };

            channel = new Channel(Host, server.Ports.Single().BoundPort, clientCredentials, options);
            client = TestService.NewClient(channel);
        }
コード例 #32
0
        public static Grpc.Core.Server Start(int port, ICategoryService categoryService, IGroupService groupService, IStudyCardService studyCardService)
        {
            var         hostName    = Dns.GetHostName();
            IPHostEntry iphostentry = Dns.GetHostByName(hostName);

            var serverPorts = iphostentry.AddressList
                              .Where(x => x.AddressFamily == AddressFamily.InterNetwork)
                              .Select(x => new ServerPort($"{x}", port, ServerCredentials.Insecure))
                              .ToList();

            if (!serverPorts.Any(x => "127.0.0.1".Equals(x.Host, StringComparison.OrdinalIgnoreCase) || "localhost".Equals(x.Host, StringComparison.OrdinalIgnoreCase)))
            {
                serverPorts.Add(new ServerPort("localhost", port, ServerCredentials.Insecure));
            }

            var server = new Grpc.Core.Server
            {
                Services =
                {
                    CategoryService.BindService(new Services.CategoryService(categoryService)),
                    GroupService.BindService(new Services.GroupService(groupService)),
                    StudyCardService.BindService(new Services.StudyCardService(studyCardService))
                }
            };

            foreach (var serverPort in serverPorts)
            {
                server.Ports.Add(serverPort);
            }

            server.Start();

            return(server);
        }
コード例 #33
0
        static void Main(string[] args)
        {
            const int port   = 9000;
            var       cacert = File.ReadAllText("Keys/ca.crt");
            var       cert   = File.ReadAllText("Keys/server.crt");
            var       key    = File.ReadAllText("Keys/server.key");

            var keypair  = new KeyCertificatePair(cert, key);
            var sslCreds = new SslServerCredentials(new List <KeyCertificatePair>
            {
                keypair
            }, cacert, false);

            Grpc.Core.Server server = new Grpc.Core.Server
            {
                Ports    = { new ServerPort("0.0.0.0", port, sslCreds) },
                Services = { BindService(new UsersService()) }
            };

            server.Start();

            Console.WriteLine("Starting server on port " + port);
            Console.WriteLine("Press any key to stop...");
            Console.ReadKey();
        }
コード例 #34
0
        public static async Task Main(string[] args)
        {
            var cancel   = new CancellationTokenSource();
            var jobQueue = new JobQueue();

            Console.WriteLine("Helium CI UI");

            var agentManager = await AgentManager.Load(Path.Combine(ConfDir, "agents"), cancel.Token);

            var projectManager = await ProjectManager.Load(Path.Combine(ConfDir, "projects"), jobQueue, cancel.Token);

            var server = new Grpc.Core.Server {
                Services = { BuildServer.BindService(new BuildServerImpl(agentManager, jobQueue)) },
                Ports    = { new ServerPort("0.0.0.0", 6000, ServerCredentials.Insecure) },
            };

            try {
                server.Start();

                try {
                    await CreateHostBuilder(agentManager, projectManager).Build().RunAsync();
                }
                finally {
                    cancel.Cancel();
                }
            }
            finally {
                await server.ShutdownAsync();
            }
        }
コード例 #35
0
        /// <summary>
        /// Initializing the GRPC service
        /// </summary>
        private static GRpcServer InitializeGrpcServer(IApiInfo apiInfo, Assembly[] searchAssemblies)
        {
            var option = new MagicOnionOptions
            {
#if DEBUG
                IsReturnExceptionStackTraceInErrorDetail = true
#else
                IsReturnExceptionStackTraceInErrorDetail = false
#endif
            };

            if (searchAssemblies == null)
            {
                searchAssemblies = new[]
                {
                    Assembly.GetEntryAssembly(),
                };
            }

            var grpcServer = new GRpcServer
            {
                Ports    = { new ServerPort(apiInfo.BindAddress, apiInfo.BindPort, ServerCredentials.Insecure) },
                Services =
                {
                    MagicOnionEngine.BuildServerServiceDefinition(
                        searchAssemblies, option)
                }
            };

            grpcServer.Start();
            return(grpcServer);
        }
    }
コード例 #36
0
ファイル: ClientServerTest.cs プロジェクト: simonkuang/grpc
 public void Init()
 {
     server = new Server();
     server.AddServiceDefinition(ServiceDefinition);
     int port = server.AddPort(Host, Server.PickUnusedPort, ServerCredentials.Insecure);
     server.Start();
     channel = new Channel(Host, port, Credentials.Insecure);
 }
コード例 #37
0
ファイル: ClientServerTest.cs プロジェクト: meisterpeeps/grpc
 public void Init()
 {
     server = new Server();
     server.AddServiceDefinition(ServiceDefinition);
     int port = server.AddListeningPort(Host, Server.PickUnusedPort);
     server.Start();
     channel = new Channel(Host, port);
 }
コード例 #38
0
ファイル: ServerTest.cs プロジェクト: hmings888/grpc
 public void StartAndShutdownServer()
 {
     Server server = new Server();
     server.AddListeningPort("localhost", Server.PickUnusedPort);
     server.Start();
     server.ShutdownAsync().Wait();
     GrpcEnvironment.Shutdown();
 }
コード例 #39
0
ファイル: ServerTest.cs プロジェクト: larsonmpdx/grpc
 public void StartAndShutdownServer()
 {
     Server server = new Server
     {
         Ports = { new ServerPort("localhost", ServerPort.PickUnused, ServerCredentials.Insecure) }
     };
     server.Start();
     server.ShutdownAsync().Wait();
 }
コード例 #40
0
ファイル: TimeoutsTest.cs プロジェクト: ksophocleous/grpc
        public void Init()
        {
            server = new Server();
            server.AddServiceDefinition(ServiceDefinition);
            int port = server.AddPort(Host, Server.PickUnusedPort, ServerCredentials.Insecure);
            server.Start();
            channel = new Channel(Host, port, Credentials.Insecure);

            stringFromServerHandlerTcs = new TaskCompletionSource<string>();
        }
コード例 #41
0
        public void Init()
        {
            helper = new MockServiceHelper();

            server = helper.GetServer();
            server.Start();
            channel = helper.GetChannel();

            headers = new Metadata { { "ascii-header", "abcdefg" } };
        }
コード例 #42
0
 public void Init()
 {
     server = new Server
     {
         Services = { Math.BindService(new MathServiceImpl()) },
         Ports = { { Host, ServerPort.PickUnused, ServerCredentials.Insecure } }
     };
     server.Start();
     channel = new Channel(Host, server.Ports.Single().BoundPort, Credentials.Insecure);
     client = Math.NewClient(channel);
 }
コード例 #43
0
 public void Init()
 {
     server = new Server
     {
         Services = { TestService.BindService(new UnimplementedTestServiceImpl()) },
         Ports = { { Host, ServerPort.PickUnused, SslServerCredentials.Insecure } }
     };
     server.Start();
     channel = new Channel(Host, server.Ports.Single().BoundPort, ChannelCredentials.Insecure);
     client = new TestService.TestServiceClient(channel);
 }
コード例 #44
0
ファイル: ServerTest.cs プロジェクト: jwatt/kythe
        public void StartAndShutdownServer()
        {
            GrpcEnvironment.Initialize();

            Server server = new Server();
            server.AddListeningPort("localhost:0");
            server.Start();
            server.ShutdownAsync().Wait();

            GrpcEnvironment.Shutdown();
        }
コード例 #45
0
        public void Init()
        {
            serviceImpl = new HealthServiceImpl();

            server = new Server();
            server.AddServiceDefinition(Grpc.Health.V1Alpha.Health.BindService(serviceImpl));
            int port = server.AddListeningPort(Host, Server.PickUnusedPort);
            server.Start();
            channel = new Channel(Host, port);

            client = Grpc.Health.V1Alpha.Health.NewClient(channel);
        }
コード例 #46
0
ファイル: TimeoutsTest.cs プロジェクト: vanliao/grpc
        public void Init()
        {
            server = new Server
            {
                Services = { ServiceDefinition },
                Ports = { { Host, ServerPort.PickUnused, ServerCredentials.Insecure } }
            };
            server.Start();
            channel = new Channel(Host, server.Ports.Single().BoundPort, Credentials.Insecure);

            stringFromServerHandlerTcs = new TaskCompletionSource<string>();
        }
コード例 #47
0
ファイル: ServerTest.cs プロジェクト: larsonmpdx/grpc
        public void CannotModifyAfterStarted()
        {
            Server server = new Server
            {
                Ports = { new ServerPort("localhost", ServerPort.PickUnused, ServerCredentials.Insecure) }
            };
            server.Start();
            Assert.Throws(typeof(InvalidOperationException), () => server.Ports.Add("localhost", 9999, ServerCredentials.Insecure));
            Assert.Throws(typeof(InvalidOperationException), () => server.Services.Add(ServerServiceDefinition.CreateBuilder("serviceName").Build()));

            server.ShutdownAsync().Wait();
        }
コード例 #48
0
      public void Start(IServiceConfiguration configuration)
      {
        BioData.BioSkyNetRepository _database = _locator.GetProcessor<BioData.BioSkyNetRepository>();
        _server = new Server
        {
          Services = { BiometricDatabaseSevice.BindService(new BiometricDatabaseSeviceImpl(_database)) },
          Ports = { new ServerPort(configuration.IpAddress, configuration.Port, ServerCredentials.Insecure) }
        };
        _server.Start();

        Console.WriteLine("BiometricDatabaseSevice server listening on port " + configuration.Port);
        Console.WriteLine("Press any key to stop the server...");
    }
コード例 #49
0
        public void Init()
        {
            server = new Server();
            server.AddServiceDefinition(TestService.BindService(new TestServiceImpl()));
            int port = server.AddPort(host, Server.PickUnusedPort, TestCredentials.CreateTestServerCredentials());
            server.Start();

            var options = new List<ChannelOption>
            {
                new ChannelOption(ChannelOptions.SslTargetNameOverride, TestCredentials.DefaultHostOverride)
            };
            channel = new Channel(host, port, TestCredentials.CreateTestClientCredentials(true), options);
            client = TestService.NewClient(channel);
        }
コード例 #50
0
        public void Init()
        {
            serviceImpl = new ReflectionServiceImpl(ServerReflection.Descriptor);

            server = new Server
            {
                Services = { ServerReflection.BindService(serviceImpl) },
                Ports = { { Host, ServerPort.PickUnused, ServerCredentials.Insecure } }
            };
            server.Start();
            channel = new Channel(Host, server.Ports.Single().BoundPort, ChannelCredentials.Insecure);

            client = new ServerReflection.ServerReflectionClient(channel);
        }
コード例 #51
0
        public void Init()
        {
            serviceImpl = new HealthServiceImpl();

            server = new Server
            {
                Services = { Grpc.Health.V1Alpha.Health.BindService(serviceImpl) },
                Ports = { { Host, ServerPort.PickUnused, ServerCredentials.Insecure } }
            };
            server.Start();
            channel = new Channel(Host, server.Ports.Single().BoundPort, ChannelCredentials.Insecure);

            client = Grpc.Health.V1Alpha.Health.NewClient(channel);
        }
コード例 #52
0
ファイル: ServerTest.cs プロジェクト: larsonmpdx/grpc
        public void PickUnusedPort()
        {
            Server server = new Server
            {
                Ports = { new ServerPort("localhost", ServerPort.PickUnused, ServerCredentials.Insecure) }
            };

            var boundPort = server.Ports.Single();
            Assert.AreEqual(0, boundPort.Port);
            Assert.Greater(boundPort.BoundPort, 0);

            server.Start();
            server.ShutdownAsync().Wait();
        }
コード例 #53
0
        private SystemWatchdog()
        {
            //start the general managing thread
            _generalThread = new Thread(new ThreadStart(ProgramManagement_Main));
            _generalThread.Start();

            // Start the gRPC server so slaves can connect
            _grpcServer = new Server
            {
                Services = { Ipc.Master.BindService(this) },
                Ports = { new ServerPort("localhost", MASTER_PORT, ServerCredentials.Insecure) }
            };
            _grpcServer.Start();
        }
コード例 #54
0
ファイル: Program.cs プロジェクト: xianglinghui/grpc
        public static void Main(string[] args)
        {
            Server server = new Server
            {
                Services = { Greeter.BindService(new GreeterImpl()) },
                Ports = { new ServerPort("localhost", Port, ServerCredentials.Insecure) }
            };
            server.Start();

            Console.WriteLine("Greeter server listening on port " + Port);
            Console.WriteLine("Press any key to stop the server...");
            Console.ReadKey();

            server.ShutdownAsync().Wait();
        }
コード例 #55
0
ファイル: ServerRunners.cs プロジェクト: xianglinghui/grpc
        /// <summary>
        /// Creates a started server runner.
        /// </summary>
        public static IServerRunner CreateStarted(ServerConfig config)
        {
            Grpc.Core.Utils.Preconditions.CheckArgument(config.ServerType == ServerType.ASYNC_SERVER);
            var credentials = config.SecurityParams != null ? TestCredentials.CreateSslServerCredentials() : ServerCredentials.Insecure;

            // TODO: qps_driver needs to setup payload properly...
            int responseSize = config.PayloadConfig != null ? config.PayloadConfig.SimpleParams.RespSize : 0;
            var server = new Server
            {
                Services = { BenchmarkService.BindService(new BenchmarkServiceImpl(responseSize)) },
                Ports = { new ServerPort(config.Host, config.Port, credentials) }
            };

            server.Start();
            return new ServerRunnerImpl(server);
        }
コード例 #56
0
        public static void Main(string[] args)
        {
            Server server = new Server
            {
                Services = { Math.BindService(new MathServiceImpl()) },
                Ports = { { Host, Port, ServerCredentials.Insecure } }
            };
            server.Start();

            Console.WriteLine("MathServer listening on port " + Port);

            Console.WriteLine("Press any key to stop the server...");
            Console.ReadKey();

            server.ShutdownAsync().Wait();
        }
コード例 #57
0
ファイル: Program.cs プロジェクト: madhon/grpc_greeter
        public static async Task MainAsync()
        {
            var server = new Server
            {
                Services = { Greeter.BindService(new GreeterImpl()) },
                Ports = { new ServerPort(Host, Port, ServerCredentials.Insecure) }
            };

            server.Start();

            Console.Out.WriteLine("Greeter server listening on port {0}", Port.ToString());
            Console.Out.WriteLine("Press any key to stop the server...");
            Console.ReadKey();

            await server.ShutdownAsync().ConfigureAwait(false);
        }
コード例 #58
0
        public void Init()
        {
            server = new Server();
            server.AddServiceDefinition(Math.BindService(new MathServiceImpl()));
            int port = server.AddPort(host, Server.PickUnusedPort, ServerCredentials.Insecure);
            server.Start();
            channel = new Channel(host, port, Credentials.Insecure);
            client = Math.NewClient(channel);

            // TODO(jtattermusch): get rid of the custom header here once we have dedicated tests
            // for header support.
            client.HeaderInterceptor = (metadata) =>
            {
                metadata.Add(new Metadata.Entry("customHeader", "abcdef"));
            };
        }
コード例 #59
0
ファイル: Program.cs プロジェクト: hongweiwang/grpc-common
        public static void Main(string[] args)
        {
            GrpcEnvironment.Initialize();

            Server server = new Server();
            server.AddServiceDefinition(Greeter.BindService(new GreeterImpl()));
            int port = server.AddListeningPort("localhost", 50051);
            server.Start();

            Console.WriteLine("Greeter server listening on port " + port);
            Console.WriteLine("Press any key to stop the server...");
            Console.ReadKey();

            server.ShutdownAsync().Wait();
            GrpcEnvironment.Shutdown();
        }
コード例 #60
0
        public void Init()
        {
            server = new Server
            {
                Services = { TestService.BindService(new TestServiceImpl()) },
                Ports = { { Host, ServerPort.PickUnused, TestCredentials.CreateSslServerCredentials() } }
            };
            server.Start();

            var options = new List<ChannelOption>
            {
                new ChannelOption(ChannelOptions.SslTargetNameOverride, TestCredentials.DefaultHostOverride)
            };
            int port = server.Ports.Single().BoundPort;
            channel = new Channel(Host, port, TestCredentials.CreateSslCredentials(), options);
            client = TestService.NewClient(channel);
        }