示例#1
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();
        }
示例#2
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);
            }
        }
示例#3
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();
                }
            }
        }
示例#4
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();
        }
示例#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 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();
        }
示例#7
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 additionRequest =>
                        {
                            Console.WriteLine($"Recieved addition request, number1 = {additionRequest.X} --- number2 = {additionRequest.Y}");
                            await responseStream.WriteAsync(new AdditionResponse {
                                Output = additionRequest.X + additionRequest.Y
                            });
                        });
                    })
                    .Build()
                }
            };

            server.Start();

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

            await server.ShutdownAsync();
        }
示例#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();
        }
示例#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();
        }
示例#10
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);
            }
        }
示例#11
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();
            }
        }
示例#12
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();
        }
示例#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)
 {
     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();
         }
     }
 }
示例#15
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();
        }
示例#16
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();
    }
示例#17
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();
            }
        }
示例#18
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();
        }
示例#19
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();

            System.Console.WriteLine("Starting server on port " + port);
            System.Console.WriteLine("Press any key to stop...");
            System.Console.ReadKey();

            server.ShutdownAsync().Wait();
        }
示例#20
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();
            }
        }
示例#21
0
 public void StartAndShutdownServer()
 {
     Server server = new Server();
     server.AddListeningPort("localhost", Server.PickUnusedPort);
     server.Start();
     server.ShutdownAsync().Wait();
     GrpcEnvironment.Shutdown();
 }
示例#22
0
 public void Stop()
 {
     Do(() => started, () =>
     {
         server.ShutdownAsync().Wait();
         Log.Info($"gRPC server was stopped");
         started = false;
     });
 }
示例#23
0
 public void StartAndShutdownServer()
 {
     Server server = new Server
     {
         Ports = { new ServerPort("localhost", ServerPort.PickUnused, ServerCredentials.Insecure) }
     };
     server.Start();
     server.ShutdownAsync().Wait();
 }
示例#24
0
        private static async Task RunServiceAsync(Grpc.Core.Server server, CancellationToken cancellationToken = default(CancellationToken))
        {
            // Start server
            server.Start();

            await AwaitCancellation(cancellationToken);

            await server.ShutdownAsync();
        }
示例#25
0
        static async Task Main(string[] args)
        {
            try
            {
                AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);

                string   username = args[0];
                string   url      = args[1];
                string[] protocolAndHostnameAndPort = url.Split("://");
                string[] hostnameAndPort            = protocolAndHostnameAndPort[1].Split(":");
                int      port                 = int.Parse(hostnameAndPort[1]);
                string   filename             = args[2] + ".txt";
                string   networkConfiguration = args[3];
                string[] lines;
                lines = System.IO.File.ReadAllLines(filename);

                CommandDispatcher commandDispatcher = new CommandDispatcher();
                ConnectionManager connectionManager = CreateConnectionManager(networkConfiguration);
                RegisterCommands(commandDispatcher, connectionManager);

                Grpc.Core.Server server = new Grpc.Core.Server
                {
                    Services =
                    {
                        PuppetMasterClientService.BindService(new PuppetmasterClientServiceImpl(connectionManager))
                    },
                    Ports = { new ServerPort(hostnameAndPort[0], port, ServerCredentials.Insecure) }
                };
                Console.WriteLine("Client listening on port " + port);

                server.Start();

                List <string> preprocessed = CommandPreprocessor.Preprocess(lines);

                await commandDispatcher.ExecuteAllAsync(preprocessed.ToArray());

                Console.WriteLine("Press ENTER to stop the client...");
                PressToExit();

                Console.WriteLine("\nShutting down...");
                server.ShutdownAsync().Wait();
            }
            catch (System.IO.FileNotFoundException e)
            {
                Console.WriteLine("ERROR: File " + args[2] + " not found in current directory.");
                Console.WriteLine(e);
                PressToExit();
                return;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                PressToExit();
                return;
            }
        }
示例#26
0
        /// <summary>
        /// stop host service
        /// </summary>
        /// <returns></returns>
        private async Task StopParentChainServer()
        {
            if (_parentChainServer == null)
            {
                return;
            }
            await _parentChainServer.ShutdownAsync();

            _parentChainServer = null;
        }
示例#27
0
        public static void GracefullyStop(Grpc.Core.Server server)
        {
            Assert.ArgumentNotNull(server, nameof(server));

            _msg.Info("Starting shut down...");

            server.ShutdownAsync().Wait();

            _msg.Info("Server shut down.");
        }
示例#28
0
        /// <summary>
        /// stop host service
        /// </summary>
        /// <returns></returns>
        private async Task StopSideChainServer()
        {
            if (_sideChainServer == null)
            {
                return;
            }
            await _sideChainServer.ShutdownAsync();

            _sideChainServer = null;
        }
示例#29
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();
        }
示例#30
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();
        }
示例#31
0
 private static void Stop(Action <Exception> whenException = null)
 {
     try
     {
         serverRegister?.RemoveRegister(serviceId);
         server?.ShutdownAsync().Wait();
     }
     catch (Exception e)
     {
         whenException?.Invoke(e);
     }
 }
示例#32
0
 public void OnDisable()
 {
     Debug.Log("Stopping server");
     // shutdown the server
     try {
         server.ShutdownAsync().Wait(1000);
         Debug.Log("Server is stopped.");
     } catch (Exception e) {
         Debug.Log("Server did not shutdown in 1s, killing it." + e);
         server.KillAsync().Wait();
     }
 }
示例#33
0
        public async Task StopAsync(CancellationToken cancellationToken)
        {
            //Log.Information($"Server Stopping {Lobby.RankMatchmaking.MatchCount}");
            //while (Lobby.RankMatchmaking.MatchCount != 0)
            //{
            //    Log.Error($"Server Stopping... please wait {Lobby.RankMatchmaking.MatchCount}");
            //    await Task.Delay(1000);
            //}

            //Log.Information($"Server Stop Complete! {Lobby.RankMatchmaking.MatchCount}");

            await _server.ShutdownAsync();
        }
示例#34
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();
        }
示例#35
0
        public void Execute()
        {
            var frontend   = new AppFrontendImpl(AppRegistry.InnerRegistry);
            var serviceDef = AppSDK.AppFrontend.BindService(frontend);
            var srv        = new Grpc.Core.Server {
                Services = { serviceDef },
                Ports    = { new ServerPort("0.0.0.0", _port, ServerCredentials.Insecure) }
            };

            srv.Start();
            Console.WriteLine($"Server is listening on {_port}. Press [enter] to exit");
            Console.ReadLine();
            srv.ShutdownAsync().Wait();
        }
示例#36
0
        public void Run(CancellationToken cancellationToken)
        {
            Console.WriteLine($"SERVER is running on {_host}:{_port}");
            _server.Start();

            using var resetEvent = new ManualResetEvent(false);
            cancellationToken.Register(() => resetEvent.Set());
            resetEvent.WaitOne();

            Console.WriteLine($"SERVER is closing ({_host}:{_port})");
            var task = Task.Run(async() => await _server.ShutdownAsync());

            Task.WaitAll(task);
        }
示例#37
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();
        }
示例#38
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();
        }
示例#39
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();
        }
示例#40
0
        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);
        }
示例#41
0
        public static void Main(string[] args)
        {
            string host = "0.0.0.0";

            Server server = new Server();
            server.AddServiceDefinition(Math.BindService(new MathServiceImpl()));
            int port = server.AddPort(host, 23456, 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();
            GrpcEnvironment.Shutdown();
        }
示例#42
0
        static void Main(string[] args)
        {
            var features = RouteGuideUtil.ParseFeatures(RouteGuideUtil.DefaultFeaturesFile);
            GrpcEnvironment.Initialize();

            Server server = new Server();
            server.AddServiceDefinition(RouteGuide.BindService(new RouteGuideImpl(features)));
            int port = server.AddListeningPort("localhost", 50052);
            server.Start();

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

            server.ShutdownAsync().Wait();
            GrpcEnvironment.Shutdown();
        }
示例#43
0
        static void Main(string[] args)
        {
            const int Port = 50052;

            var features = RouteGuideUtil.ParseFeatures(RouteGuideUtil.DefaultFeaturesFile);

            Server server = new Server
            {
                Services = { RouteGuide.BindService(new RouteGuideImpl(features)) },
                Ports = { new ServerPort("localhost", Port, ServerCredentials.Insecure) }
            };
            server.Start();

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

            server.ShutdownAsync().Wait();
        }
示例#44
0
        static void Main(string[] args)
        {
            var gameAdminService = new GameAdminServiceServer(
                new HardcodedAccountRepository(),
                new HardcodedChatMessageRepository());

            const int port = 1337;
            var rpcServer = new Grpc.Core.Server
            {
                Services = { GameAdminService.BindService(gameAdminService) },
                Ports = { new Grpc.Core.ServerPort("localhost", port, ServerCredentials.Insecure) }
            };
            rpcServer.Start();

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

            Log("GameAdminService shutting down");
            rpcServer.ShutdownAsync().Wait();
        }
 public void UnstartedServerCanBeShutdown()
 {
     var server = new Server();
     server.ShutdownAsync().Wait();
     Assert.Throws(typeof(InvalidOperationException), () => server.Start());
 }
示例#46
0
        private async Task RunAsync()
        {
            string host = "0.0.0.0";
            int port = options.DriverPort;

            var tcs = new TaskCompletionSource<object>();
            var workerServiceImpl = new WorkerServiceImpl(() => { Task.Run(() => tcs.SetResult(null)); });
                
            var server = new Server
            {
                Services = { WorkerService.BindService(workerServiceImpl) },
                Ports = { new ServerPort(host, options.DriverPort, ServerCredentials.Insecure )}
            };
            int boundPort = server.Ports.Single().BoundPort;
            Console.WriteLine("Running qps worker server on " + string.Format("{0}:{1}", host, boundPort));
            server.Start();
            await tcs.Task;
            await server.ShutdownAsync();
        }
示例#47
0
        public void UnaryCallPerformance()
        {
            Server server = new Server();
            server.AddServiceDefinition(
                ServerServiceDefinition.CreateBuilder("someService")
                .AddMethod(unaryEchoStringMethod, HandleUnaryEchoString).Build());

            int port = server.AddPort(host + ":0");
            server.Start();

            using (Channel channel = new Channel(host + ":" + port))
            {
                var call = new Call<string, string>(unaryEchoStringMethod, channel);
                BenchmarkUtil.RunBenchmark(100, 1000,
                                           () => { Calls.BlockingUnaryCall(call, "ABC", default(CancellationToken)); });
            }

            server.ShutdownAsync().Wait();
        }
示例#48
0
文件: QpsWorker.cs 项目: nerdrew/grpc
        private async Task RunAsync()
        {
            // (ThreadPoolSize == ProcessorCount) gives best throughput in benchmarks
            // and doesn't seem to harm performance even when server and client
            // are running on the same machine.
            GrpcEnvironment.SetThreadPoolSize(Environment.ProcessorCount);

            string host = "0.0.0.0";
            int port = options.DriverPort;

            var tcs = new TaskCompletionSource<object>();
            var workerServiceImpl = new WorkerServiceImpl(() => { Task.Run(() => tcs.SetResult(null)); });
                
            var server = new Server
            {
                Services = { WorkerService.BindService(workerServiceImpl) },
                Ports = { new ServerPort(host, options.DriverPort, ServerCredentials.Insecure )}
            };
            int boundPort = server.Ports.Single().BoundPort;
            Console.WriteLine("Running qps worker server on " + string.Format("{0}:{1}", host, boundPort));
            server.Start();
            await tcs.Task;
            await server.ShutdownAsync();
        }
示例#49
0
        public void UnaryCall()
        {
            Server server = new Server();
            server.AddServiceDefinition(
                ServerServiceDefinition.CreateBuilder("someService")
                    .AddMethod(unaryEchoStringMethod, HandleUnaryEchoString).Build());

            int port = server.AddPort(host + ":0");
            server.Start();

            using (Channel channel = new Channel(host + ":" + port))
            {
                var call = new Call<string, string>(unaryEchoStringMethod, channel);

                Assert.AreEqual("ABC", Calls.BlockingUnaryCall(call, "ABC", default(CancellationToken)));

                Assert.AreEqual("abcdef", Calls.BlockingUnaryCall(call, "abcdef", default(CancellationToken)));
            }

            server.ShutdownAsync().Wait();
        }
示例#50
0
        public void UnknownMethodHandler()
        {
            Server server = new Server();
            server.AddServiceDefinition(
                ServerServiceDefinition.CreateBuilder("someService").Build());

            int port = server.AddPort(host + ":0");
            server.Start();

            using (Channel channel = new Channel(host + ":" + port))
            {
                var call = new Call<string, string>(unaryEchoStringMethod, channel);

                try {
                    Calls.BlockingUnaryCall(call, "ABC", default(CancellationToken));
                    Assert.Fail();
                } catch(RpcException e) {
                    Assert.AreEqual(StatusCode.Unimplemented, e.Status.StatusCode);
                }
            }

            server.ShutdownAsync().Wait();
        }
示例#51
0
        async Task Run()
        {
            var metricsServer = new Server()
            {
                Services = { MetricsService.BindService(new MetricsServiceImpl(histogram)) },
                Ports = { { "[::]", options.MetricsPort, ServerCredentials.Insecure } }
            };
            metricsServer.Start();

            if (options.TestDurationSecs >= 0)
            {
                finishedTokenSource.CancelAfter(TimeSpan.FromSeconds(options.TestDurationSecs));
            }

            var tasks = new List<Task>();
            var channels = new List<Channel>();
            foreach (var serverAddress in serverAddresses)
            {
                for (int i = 0; i < options.NumChannelsPerServer; i++)
                {
                    var channel = new Channel(serverAddress, ChannelCredentials.Insecure);
                    channels.Add(channel);
                    for (int j = 0; j < options.NumStubsPerChannel; j++)
                    {
                        var client = TestService.NewClient(channel);
                        var task = Task.Factory.StartNew(() => RunBodyAsync(client).GetAwaiter().GetResult(),
                            TaskCreationOptions.LongRunning);
                        tasks.Add(task);  
                    }
                }
            }
            await Task.WhenAll(tasks);

            foreach (var channel in channels)
            {
                await channel.ShutdownAsync();
            }

            await metricsServer.ShutdownAsync();
        }