Exemplo n.º 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);
        }
Exemplo n.º 2
0
        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();
                }
            }
        }
Exemplo n.º 3
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();
        }
Exemplo n.º 4
0
 public void Init()
 {
     helper = new MockServiceHelper(Host);
     server = helper.GetServer();
     server.Start();
     channel = helper.GetChannel();
 }
Exemplo n.º 5
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();
            }
        }
Exemplo n.º 6
0
        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();
        }
Exemplo n.º 7
0
        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();
        }
Exemplo n.º 8
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();
        }
Exemplo n.º 9
0
        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();
        }
Exemplo n.º 10
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();
 }
Exemplo n.º 11
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);
        }
Exemplo n.º 12
0
 public GrpcManager(IGrpcConfiguration configuration, ILogger logger)
 {
     this.logger     = logger;
     this.ports      = configuration.Endpoints.Select(x => new ServerPort(x.Host, x.Port, ServerCredentials.Insecure)).ToArray();
     this.grpcServer = this.CreateServer(this.services);
     logger.Info($"gRPC Server started on {configuration.Endpoints[0].Host}:{configuration.Endpoints[0].Port}");
 }
Exemplo n.º 13
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();
        }
Exemplo n.º 14
0
        /// <summary>
        /// Build server grpc
        /// </summary>
        /// <param name="provider"></param>
        /// <param name="cfg"></param>
        /// <returns></returns>
        internal static Grpc.Core.Server Build(IServiceProvider provider, GrpcServerConfiguration cfg)
        {
            // get logger if needed
            var logger = (cfg.Options?.LogRequests ?? false) ? provider.GetService <ILoggerFactory>()?.CreateLogger("GrpcServerRequests") : null;

            // create services for interfaces
            var interfacesServices = CreateServiceDefinitionForInterfaces(provider, cfg);

            // implemented services
            var protoGenServices = CreateServicesDefinitionsForProtoGen(provider, cfg);

            // create grpc server
            var server = new Grpc.Core.Server()
            {
                Ports    = { { cfg.Host.Url, cfg.Host.Port, ServerCredentials.Insecure } },
                Services = {}
            };

            // add services to server
            interfacesServices.ForEach(s => server.Services.Add(s));
            protoGenServices.ForEach(s => server.Services.Add(s));

            // return server
            return(server);
        }
Exemplo n.º 15
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();
            }
        }
Exemplo n.º 16
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();
        }
Exemplo n.º 17
0
        /// <inheritdoc />
        public Task <string> OpenAsync(CancellationToken cancellationToken)
        {
            var serviceDefinition = this.createService();

            this.server = new Grpc.Core.Server
            {
                Services =
                {
                    serviceDefinition,
                },
                Ports =
                {
                    new Grpc.Core.ServerPort("0.0.0.0", Grpc.Core.ServerPort.PickUnused, Grpc.Core.ServerCredentials.Insecure),
                },
            };

            this.server.Start();

            int workerCount, completionPortCount;

            ThreadPool.GetMinThreads(out workerCount, out completionPortCount);
            ThreadPool.SetMinThreads(64, completionPortCount);

            return(Task.FromResult($"grpc://{this.hostIpAddress}:{this.server.Ports.First().BoundPort}"));
        }
Exemplo n.º 18
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();
        }
Exemplo n.º 19
0
        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();
        }
Exemplo n.º 20
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);
        }
Exemplo n.º 21
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);
            }
        }
Exemplo n.º 22
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();
        }
Exemplo n.º 23
0
        public async Task ManyStreamingServerCallsSingleClientTest()
        {
            GrpcCore.Server server = this.StartSimpleServiceServer();

            GrpcCore.Channel channel = new GrpcCore.Channel($"127.0.0.1:{GrpcTestPort}", GrpcCore.ChannelCredentials.Insecure);
            var client = new SimpleCoreService.SimpleCoreServiceClient(channel);

            List <Task> activeCalls      = new List <Task>();
            const int   TotalClientCalls = 100;
            const int   ClientId         = 0;
            TaskCompletionSource <bool> tasksQueuedCompletionSource = new TaskCompletionSource <bool>();

            var callsCounter = new CallsCounter {
                nTotalCalls = TotalClientCalls, tasksQueueTask = tasksQueuedCompletionSource.Task
            };

            this.activeCallCountersDictionary.Add(ClientId, callsCounter);

            for (int i = 0; i < 100; i++)
            {
                activeCalls.Add(MakeStreamingServerCalls(client, ClientId, 10, 10));
                lock (callsCounter)
                {
                    callsCounter.nActiveCalls++;
                }
            }
            Assert.AreEqual(TotalClientCalls, callsCounter.nActiveCalls);
            tasksQueuedCompletionSource.SetResult(true);

            await Task.WhenAll(activeCalls);

            Assert.AreEqual(0, callsCounter.nActiveCalls);

            await server.ShutdownAsync();
        }
Exemplo n.º 24
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();
        }
Exemplo n.º 25
0
        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);
        }
Exemplo n.º 26
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);
        }
    }
Exemplo n.º 27
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();
            }
        }
Exemplo n.º 28
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);
        }
Exemplo n.º 29
0
        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();
        }
Exemplo n.º 30
0
    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();
    }
Exemplo n.º 31
0
        /// <summary>
        /// Stops the and deregister.
        /// </summary>
        /// <param name="server">The server.</param>
        /// <param name="stopServer">The stop server.</param>
        /// <returns></returns>
        /// <exception cref="Exception">当前服务没有注册,或者是已经被反注册过..</exception>
        public static async Task <Server> StopAndDeregister(this Grpc.Core.Server server,
                                                            Action <Server> stopServer = null)
        {
            if (!serviceDict.ContainsKey(server.GetHashCode()))
            {
                throw new Exception("当前服务没有注册,或者是已经被反注册过..");
            }

            await serviceDict[server.GetHashCode()].Deregister();

            serviceDict.Remove(server.GetHashCode());
            InnerLogger.Log(LoggerLevel.Info, "反注册服务发现");

            if (stopServer == null)
            {
                await server.KillAsync();
            }
            else
            {
                stopServer(server);
            }

            InnerLogger.Log(LoggerLevel.Info, "grpc服务停止");
            return(server);
        }
Exemplo n.º 32
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);
            }
        }
Exemplo n.º 33
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();
        }
Exemplo n.º 34
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();
         }
     }
 }
Exemplo n.º 35
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();
        }
Exemplo n.º 36
0
 public void Init()
 {
     server = new Server();
     server.AddServiceDefinition(ServiceDefinition);
     int port = server.AddListeningPort(Host, Server.PickUnusedPort);
     server.Start();
     channel = new Channel(Host, port);
 }
Exemplo n.º 37
0
 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);
 }
Exemplo n.º 38
0
 public void StartAndShutdownServer()
 {
     Server server = new Server();
     server.AddListeningPort("localhost", Server.PickUnusedPort);
     server.Start();
     server.ShutdownAsync().Wait();
     GrpcEnvironment.Shutdown();
 }
 public ServerRpcNew(Server server, CallSafeHandle call, string method, string host, Timespec deadline, Metadata requestMetadata)
 {
     this.server = server;
     this.call = call;
     this.method = method;
     this.host = host;
     this.deadline = deadline;
     this.requestMetadata = requestMetadata;
 }
Exemplo n.º 40
0
 public void StartAndShutdownServer()
 {
     Server server = new Server
     {
         Ports = { new ServerPort("localhost", ServerPort.PickUnused, ServerCredentials.Insecure) }
     };
     server.Start();
     server.ShutdownAsync().Wait();
 }
Exemplo n.º 41
0
        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>();
        }
        public void Init()
        {
            helper = new MockServiceHelper();

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

            headers = new Metadata { { "ascii-header", "abcdefg" } };
        }
 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);
 }
Exemplo n.º 44
0
        public void StartAndShutdownServer()
        {
            GrpcEnvironment.Initialize();

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

            GrpcEnvironment.Shutdown();
        }
Exemplo n.º 45
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);
 }
Exemplo n.º 46
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);
        }
Exemplo n.º 47
0
        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>();
        }
Exemplo n.º 48
0
        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();
        }
      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...");
    }
Exemplo n.º 50
0
        // Gets data of server_rpc_new completion.
        public ServerRpcNew GetServerRpcNew(Server server)
        {
            var call = Native.grpcsharp_request_call_context_call(this);

            var method = Marshal.PtrToStringAnsi(Native.grpcsharp_request_call_context_method(this));
            var host = Marshal.PtrToStringAnsi(Native.grpcsharp_request_call_context_host(this));
            var deadline = Native.grpcsharp_request_call_context_deadline(this);

            IntPtr metadataArrayPtr = Native.grpcsharp_request_call_context_request_metadata(this);
            var metadata = MetadataArraySafeHandle.ReadMetadataFromPtrUnsafe(metadataArrayPtr);

            return new ServerRpcNew(server, call, method, host, deadline, metadata);
        }
Exemplo n.º 51
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);
        }
Exemplo n.º 52
0
        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();
        }
Exemplo n.º 53
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);
        }
Exemplo n.º 54
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);
        }
Exemplo n.º 55
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();
        }
Exemplo n.º 56
0
        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();
        }
Exemplo n.º 57
0
        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();
        }
Exemplo n.º 58
0
        /// <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);
        }
Exemplo n.º 59
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"));
            };
        }
Exemplo n.º 60
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();
        }