Ejemplo n.º 1
0
 public GreeterImpl(string instanceName, GreetingFederator federator)
 {
     this.instanceName = instanceName;
     this.federator    = federator;
 }
Ejemplo n.º 2
0
        public static void Main(string[] args)
        {
            int port;

            if (!int.TryParse(Environment.GetEnvironmentVariable("GREETINGS_PORT"), out port))
            {
                port = DefaultPort;
            }
            var instanceName = Environment.GetEnvironmentVariable("GREETINGS_NAME") ?? Environment.MachineName;

            var downStreamHosts = Environment.GetEnvironmentVariable("GREETINGS_DOWNSTREAM_HOSTS") ?? string.Empty;

            int helloDelay;

            if (!int.TryParse(Environment.GetEnvironmentVariable("GREETINGS_DELAYMS"), out helloDelay))
            {
                helloDelay = 0;
            }

            var federator = new GreetingFederator(downStreamHosts, instanceName);

            Server server = new Server
            {
                Services = { Greeter.BindService(new GreeterImpl(instanceName, federator)) },
                Ports    = { new ServerPort("0.0.0.0", port, ServerCredentials.Insecure) }
            };

            server.Start();

            Console.WriteLine($"Greeter server [{instanceName}] listening on port [{port}]");

            var cts = new CancellationTokenSource();

            if (helloDelay != 0)
            {
                int    numBytes;
                string payload = string.Empty;
                if (int.TryParse(Environment.GetEnvironmentVariable("GREETINGS_NUMBYTES"), out numBytes))
                {
                    if (numBytes > 0)
                    {
                        payload = new string('*', numBytes);
                    }
                }

                Console.WriteLine($"Greeter server [{instanceName}] will federate as client");
                Task.Run(() => {
                    while (!cts.IsCancellationRequested)
                    {
                        federator.SayHello(new HelloRequest {
                            Name = payload
                        });
                        if (helloDelay > 0)
                        {
                            Task.Delay(helloDelay, cts.Token);
                        }
                    }
                }, cts.Token);
            }

            var syncTask = new TaskCompletionSource <bool>();

            System.Runtime.Loader.AssemblyLoadContext.Default.Unloading += (context) => {
                Console.WriteLine("Greeter server received kill signal...");
                cts.Cancel();
                server.ShutdownAsync().Wait();
                syncTask.SetResult(true);
            };

            syncTask.Task.Wait(-1);
            Console.WriteLine("Greeter server stopped");
        }