Ejemplo n.º 1
0
        static async Task Main(string[] args)
        {
            GrpcEnvironment.SetLogger(new Grpc.Core.Logging.ConsoleLogger());


            //// you can use new HostBuilder() instead of CreateDefaultBuilder
            await new HostBuilder()
            .UseMagicOnion()
            .RunConsoleAsync();


            //MagicOnionServiceDefinition service = MagicOnionEngine.BuildServerServiceDefinition(

            //    new[] { typeof(IMyFirstService).Assembly },  // 加载引用程序集
            //    new MagicOnionOptions(true)
            //    {
            //        MagicOnionLogger = new MagicOnionLogToGrpcLogger()
            //    }
            //);

            // setup MagicOnion and option.
            var service = MagicOnionEngine.BuildServerServiceDefinition(isReturnExceptionStackTraceInErrorDetail: true);

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

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

            // and wait.
            Console.ReadLine();
        }
 public void Dispose()
 {
     if (_server == null)
     {
         return;
     }
     AsyncHelper.RunSync(() => _server.ShutdownAsync());
     _server   = null;
     IsStarted = false;
 }
Ejemplo n.º 3
0
        public GrpcHost <TService> Build()
        {
            var server = new global::Grpc.Core.Server
            {
                Ports    = { { _options.Url, _options.Port, ServerCredentials.Insecure } },
                Services =
                {
                    _builder.Build()
                }
            };

            return(new GrpcHost <TService>(server));
        }
Ejemplo n.º 4
0
    static void Main()
    {
        GrpcEnvironment.SetLogger(new Grpc.Core.Logging.ConsoleLogger());
        var service = MagicOnionEngine.BuildServerServiceDefinition(isReturnExceptionStackTraceInErrorDetail: true);
        var server  = new global::Grpc.Core.Server
        {
            Services = { service },
            Ports    = { new ServerPort("localhost", 12345, ServerCredentials.Insecure) }
        };

        server.Start();
        Console.ReadLine();
    }
Ejemplo n.º 5
0
        static void Main(string[] args)
        {
            Console.WriteLine("RPC服务端已启动。。。");

            var service = MagicOnionEngine.BuildServerServiceDefinition(isReturnExceptionStackTraceInErrorDetail: true);
            var server  = new global::Grpc.Core.Server
            {
                Services = { service },
                Ports    = { new ServerPort("localhost", 19021, ServerCredentials.Insecure) }
            };

            server.Start();

            Console.ReadLine();
        }
Ejemplo n.º 6
0
        static void Main(string[] args)
        {
            const int port = 1337;
            var rpcServer = new global::Grpc.Core.Server
            {
                Services = { BenchmarkService.BindService(new BenchmarkServiceServer()) },
                Ports = { new ServerPort("localhost", port, ServerCredentials.Insecure) }
            };
            rpcServer.Start();

            Console.WriteLine("BenchmarkService server listening on port " + port);
            Console.WriteLine("Press any key to stop the server...");
            Console.ReadKey();
            rpcServer.ShutdownAsync().Wait();
        }
Ejemplo n.º 7
0
        private void StartGrpcServer()
        {
            if (Port == 0)
            {
                Port = Util.FreeTcpPort();
            }
            var grpcServer = new global::Grpc.Core.Server
            {
                Services = { ChatClientService.BindService(this) },
                Ports    = { new ServerPort(Host, Port, ServerCredentials.Insecure) }
            };

            grpcServer.Start();
            _logger?.LogInformation($"Start gRPC Server @ {Host}:{Port}");
        }
 public GrpcServer(string host, int port, ServerServiceDefinition serviceDefinition)
 {
     _server = new global::Grpc.Core.Server
     {
         Services =
         {
             serviceDefinition,
         },
         Ports = { new ServerPort(host, port, ServerCredentials.Insecure) }
     };
     Features = new FeatureCollection();
     Features.Set <IServerAddressesFeature>(new ServerAddressesFeature {
         Addresses = { $"http://{host}:{port}" }
     });
 }
Ejemplo n.º 9
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime lifetime)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvcWithDefaultRoute();

            lifetime.ApplicationStarted.Register(() => {
                var service = MagicOnionEngine.BuildServerServiceDefinition(new[] { typeof(Startup).Assembly }, new MagicOnionOptions(true)
                {
                    // MagicOnionLogger = new MagicOnionLogToGrpcLogger(),
                    MagicOnionLogger = new MagicOnionLogToGrpcLoggerWithNamedDataDump(),
                    GlobalFilters    = new MagicOnionFilterAttribute[]
                    {
                    },
                    EnableCurrentContext = true
                });

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

                server.Start();

                IConsulClient consul = new ConsulClient(r => {
                    r.Address = new Uri("http://10.10.10.45:8500");
                });

                consul.Agent.ServiceRegister(new AgentServiceRegistration {
                    ID      = "1111",
                    Address = "10.10.10.91",
                    Port    = 12345,
                    Tags    = new[] { "grpc" },
                    Name    = "DemoServer",
                    Check   = new AgentServiceCheck {
                        DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5),
                        Interval = TimeSpan.FromSeconds(10),
                        Status   = HealthStatus.Passing,
                        Timeout  = TimeSpan.FromSeconds(5),
                        HTTP     = $"http://10.10.10.91:20000/home"
                    }
                }).Wait();
            });
        }
Ejemplo n.º 10
0
        static void Main(string[] args)
        {
            Console.WriteLine("RPC DBServer Start UP . . . . . . ");
            Utility.Debug.SetHelper(new DBDebugHelper());
            InitDBManager();
            var service = MagicOnionEngine.BuildServerServiceDefinition(isReturnExceptionStackTraceInErrorDetail: true);
            var server  = new global::Grpc.Core.Server
            {
                Services = { service },
                Ports    = { new ServerPort("localhost", 14567, ServerCredentials.Insecure) }
            };

            server.Start();
            while (true)
            {
            }
        }
            public NotificationServiceGrpcServer()
            {
                // Locate required files and set true to enable SSL
                //var secure = false;

                m_server = new global::Grpc.Core.Server
                {
                    Services =
                    {
                        Notification.BindService(this)
                        .Intercept(new IpAddressAuthenticator())
                    },
                    Ports =
                    {
                        new ServerPort("localhost", Port, ServerCredentials.Insecure)
                    }
                };
            }
Ejemplo n.º 12
0
        public static async Task Main()
        {
            var host = new HostBuilder()
                       .ConfigureLogging(logging => logging.AddConsole())
                       .ConfigureServices(services =>
            {
                var server = new global::Grpc.Core.Server
                {
                    Services = { String.BindService(new StringService()) },
                    Ports    = { new ServerPort("localhost", 50001, ServerCredentials.Insecure) }
                };

                services.AddSingleton(server);
                services.AddHostedService <HostedGrpcService>();
            });

            await host.RunConsoleAsync();
        }
Ejemplo n.º 13
0
        static void Main(string[] args)
        {
            Console.WriteLine("The gRPC server is starting.");

            var server = new GoogleGrpc.Core.Server
            {
                Services = { Adder.BindService(new AdderService()) },
                Ports    = { new GoogleGrpc.Core.ServerPort("localhost", 50000, GoogleGrpc.Core.ServerCredentials.Insecure) }
            };

            server.Start();

            Console.WriteLine("The gRPC server is listening.");
            Console.WriteLine();
            Console.WriteLine("Press Enter to shut down the server.");
            Console.ReadLine();

            server.ShutdownAsync().Wait();
        }
Ejemplo n.º 14
0
        private static void RunHost()
        {
            MagicOnionServiceDefinition service = MagicOnionEngine.BuildServerServiceDefinition(
                new[] { typeof(UserAccessGrpc) },
                new MagicOnionOptions(isReturnExceptionStackTraceInErrorDetail: true));

            // SSL gRPC
            string caCrt          = File.ReadAllText(EnvVars.CaCrtPath());
            string serverCrt      = File.ReadAllText(EnvVars.ServerCrtPath());
            string serverKey      = File.ReadAllText(EnvVars.ServerKeyPath());
            var    keyPair        = new KeyCertificatePair(serverCrt, serverKey);
            var    sslCredentials = new SslServerCredentials(new List <KeyCertificatePair>()
            {
                keyPair
            }, caCrt, false);

            int localPort = EnvVars.LocalPort(@"UserAccessPort");

            var server = new global::Grpc.Core.Server
            {
                Services = { service },
                Ports    = { new ServerPort("0.0.0.0", localPort, sslCredentials) }
            };

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

            Log.Information($"Server listening on port {localPort}");

            var cts = new CancellationTokenSource();

            var syncTask = new TaskCompletionSource <bool>();

            System.Runtime.Loader.AssemblyLoadContext.Default.Unloading += (context) =>
            {
                Log.Information("Greeter server received kill signal...");
                cts.Cancel();
                server.ShutdownAsync().Wait();
                syncTask.SetResult(true);
            };
            syncTask.Task.Wait(-1);
            Log.Information("Greeter server stopped");
        }
Ejemplo n.º 15
0
        static void Main(string[] args)
        {
            Console.WriteLine("Input IP Server: ");
            string ipAddress = Console.ReadLine();

            GrpcEnvironment.SetLogger(new Grpc.Core.Logging.ConsoleLogger());

            var service = MagicOnionEngine.BuildServerServiceDefinition(isReturnExceptionStackTraceInErrorDetail: true);

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

            server.Start();
            Console.WriteLine("Server started");
            Console.ReadLine();
        }
Ejemplo n.º 16
0
        static void Main(string[] args)
        {
            Console.WriteLine("Server:::");

            //Environment.SetEnvironmentVariable("GRPC_VERBOSITY", "DEBUG");
            //Environment.SetEnvironmentVariable("GRPC_TRACE", "all");

            Environment.SetEnvironmentVariable("SETTINGS_MAX_HEADER_LIST_SIZE", "1000000");

            GrpcEnvironment.SetLogger(new ConsoleLogger());

            var service = MagicOnionEngine.BuildServerServiceDefinition(new MagicOnionOptions(true)
            {
                // MagicOnionLogger = new MagicOnionLogToGrpcLogger(),
                MagicOnionLogger = new MagicOnionLogToGrpcLoggerWithNamedDataDump(),
                GlobalFilters    = new MagicOnionFilterAttribute[]
                {
                },
                EnableCurrentContext = true
            });

            var server = new global::Grpc.Core.Server
            {
                Services = { service },
                Ports    = { new ServerPort(Configuration.GrpcHost, 12345, ServerCredentials.Insecure) }
            };

            server.Start();

            var webHost = new WebHostBuilder()
                          .ConfigureServices(collection =>
            {
                collection.Add(new ServiceDescriptor(typeof(MagicOnionServiceDefinition), service));
            })
                          //.UseWebListener()
                          .UseHttpSys()
                          .UseStartup <Startup>()
                          .UseUrls(Configuration.GatewayHost)
                          .Build();

            webHost.Run();
        }
Ejemplo n.º 17
0
        static void Main(string[] args)
        {
            var serviceProvider = new ServiceCollection()
                                  .AddInfrastructure()
                                  .BuildServiceProvider();

            var server = new global::Grpc.Core.Server
            {
                Services = { ProductionLineService.BindService(new ProductionLineImpl(serviceProvider)) },
                Ports    = { new ServerPort("localhost", Port, ServerCredentials.Insecure) }
            };

            server.Start();

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

            server.ShutdownAsync().Wait();
        }
Ejemplo n.º 18
0
        static void Main(string[] args)
        {
            const int Port = 50052;

            Console.WriteLine("Starting VirtualWallet server!");

            var server = new global::Grpc.Core.Server
            {
                // TODO: Bind all service implementations here.
                Services = { LegalPersonService.BindService(new LegalPersonServiceImpl()) },
                Ports    = { new ServerPort("localhost", Port, ServerCredentials.Insecure) }
            };

            server.Start();

            Console.WriteLine("VirtualWallet Server listening at port " + Port);
            Console.WriteLine("Press any key to stop the server...");
            Console.ReadKey();

            server.ShutdownAsync().Wait();
        }
        public async Task StartAsync(int listeningPort)
        {
            _server = new global::Grpc.Core.Server
            {
                Ports =
                {
                    new ServerPort(IPAddress.Any.ToString(), listeningPort, ServerCredentials.Insecure)
                },
                Services =
                {
                    ParentChainRpc.BindService(_grpcParentChainServerBase),
                    SideChainRpc.BindService(_grpcSideChainServerBase),
                    BasicCrossChainRpc.BindService(_grpcBasicServerBase)
                }
            };

            await Task.Run(() => _server.Start());

            Logger.LogInformation($"Grpc cross chain server started, listening at {listeningPort}");
            IsStarted = true;
        }
Ejemplo n.º 20
0
        static void Main(string[] args)
        {
            Console.WriteLine("启动服务器...");
            //コンソールにログを表示させる
            GrpcEnvironment.SetLogger(new Grpc.Core.Logging.ConsoleLogger());

            var service = MagicOnionEngine.BuildServerServiceDefinition(isReturnExceptionStackTraceInErrorDetail: true);

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

            // MagicOnion起動
            server.Start();
            Console.WriteLine("启动完成...");
            // コンソールアプリが落ちないようにReadLineで待つ
            Console.ReadLine();
        }
Ejemplo n.º 21
0
        void StartTask(CancellationToken token)
        {
            if (_Server != null)
            {
                // already running
                return;
            }
            var newServer = new global::Grpc.Core.Server(_ChannelOptions)
            {
                Services = { _ServiceDefinition },
            };

            // if another server is set in another thread, just leave it.
            if (null == Interlocked.CompareExchange(ref _Server, newServer, null))
            {
                foreach (var port in _Ports)
                {
                    _Server.Ports.Add(port);
                }
                _Server.Start();
            }
        }
Ejemplo n.º 22
0
        public GrpcServerServiceImpl(
            Server server,
            IServiceProvider serviceProvider,
            string host, int port)
        {
            _server = server;
            _logger = serviceProvider.GetService <ILoggerFactory>()?
                      .CreateLogger("Chat.GrpcServerService");

            if (port == 0)
            {
                port = Util.FreeTcpPort();
            }
            var grpcServer = new global::Grpc.Core.Server
            {
                Services = { ChatServerService.BindService(this) },
                Ports    = { new ServerPort(host, port, ServerCredentials.Insecure) }
            };

            grpcServer.Start();
            _logger?.LogInformation($"Start gRPC Server @ {host}:{port}");
        }
Ejemplo n.º 23
0
        static void Main(string[] args)
        {
            GrpcEnvironment.SetLogger(new Grpc.Core.Logging.ConsoleLogger());

            var service = MagicOnionEngine.BuildServerServiceDefinition(isReturnExceptionStackTraceInErrorDetail: true);

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

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

            // sample, launch server/client in same app.
            Task.Run(() =>
            {
                ClientImpl();
            });

            Console.ReadLine();
        }
Ejemplo n.º 24
0
        private void StartServerIfNotStarted()
        {
            if (_server != null)
            {
                return;
            }

            GrpcEnvironment.SetLogger(new Logger(_consoleHandle));

            _server = new Srv
            {
                Services =
                {
                    Grpc.Editor.Console.BindService(_consoleImpl),
                    Grpc.Editor.ProjectManager.BindService(_projectManagerImpl),
                    Grpc.Editor.Presence.BindService(_presenceImpl),
                    Grpc.Editor.GameHoster.BindService(_gameHosterImpl),
                },
                Ports = { new ServerPort("localhost", 0, ServerCredentials.Insecure) }
            };
            _server.Start();

            _serverUrl = "localhost:" + _server.Ports.Select(x => x.BoundPort).First();
        }
Ejemplo n.º 25
0
 public HostedGrpcService(global::Grpc.Core.Server server, ILogger <HostedGrpcService> logger)
 {
     this.server = server;
     this.logger = logger;
 }
Ejemplo n.º 26
0
        public static int RealMain(string[] args)
        {
            int?trackProcessId = null;

            Console.Error.WriteLine("ExtHost RealMain called with: " + args.Aggregate((a, b) => a + " " + b));
            var    argsList     = new Queue <string>(args);
            string editorUrl    = null;
            string assemblyFile = null;

            while (argsList.Count > 0)
            {
                var arg = argsList.Dequeue();
                switch (arg)
                {
                case "--trace":
                {
                    var pid     = argsList.Dequeue();
                    var process = Process.GetProcessById(int.Parse(pid));
                    process.Exited += (sender, e) =>
                    {
                        Console.Error.WriteLine("Parent process " + pid + " has exited, closing extension host process.");
                        Environment.Exit(0);
                    };
                    process.EnableRaisingEvents = true;
                    if (process.HasExited)
                    {
                        Console.Error.WriteLine("Parent process " + pid + " has exited, closing extension host process.");
                        Environment.Exit(0);
                    }
                    break;
                }

                case "--debug":
                    Debugger.Launch();
                    break;

                case "--editor-url":
                    editorUrl = argsList.Dequeue();
                    break;

                case "--assembly-path":
                    assemblyFile = argsList.Dequeue();
                    break;
                }
            }

            AppDomain.CurrentDomain.UnhandledException += (sender, e) =>
            {
                Console.Error.WriteLine(e.ExceptionObject);
            };

            if (editorUrl == null || assemblyFile == null)
            {
                System.Console.Error.WriteLine("Editor URL or assembly file not specified");
                return(1);
            }

            System.Console.Error.WriteLine("Starting extension host...");
            System.Console.Error.WriteLine("Editor URL is: {0}", editorUrl);
            System.Console.Error.WriteLine("Assembly path is: {0}", assemblyFile);

            System.Console.Error.WriteLine("Loading assembly from: {0}", assemblyFile);
            var assembly = Assembly.LoadFrom(assemblyFile);

            // Find the attributes that describe the extensions provided by this assembly.
            var editorExtensions = new List <IEditorExtension>();

            foreach (var attr in assembly.GetCustomAttributes <ExtensionAttribute>())
            {
                try
                {
                    editorExtensions.Add((IEditorExtension)Activator.CreateInstance(attr.Type));
                }
                catch (Exception e)
                {
                    System.Console.Error.WriteLine(e);
                }
            }

            System.Console.Error.WriteLine("Configuring kernel...");

            var kernel = new StandardKernel();

            kernel.Bind <IEditorClientProvider>().To <EditorClientProvider>().InSingletonScope();
            kernel.Bind <IProjectManager>().To <ProjectManager>().InSingletonScope();
            kernel.Bind <IWantsUpdateSignal>().To <ProjectManagerUpdateSignal>().InSingletonScope();
            kernel.Bind <IWantsUpdateSignal>().To <PresenceCheckerUpdateSignal>().InSingletonScope();
            kernel.Bind <Editor.Api.Version1.Core.IConsoleHandle>().To <ConsoleHandle>().InSingletonScope();
            foreach (var ext in editorExtensions)
            {
                ext.RegisterServices(kernel);
            }

            System.Console.Error.WriteLine("Configuring editor client provider with URL: {0}", editorUrl);
            var editorClientProvider = kernel.Get <IEditorClientProvider>();

            editorClientProvider.CreateChannel(editorUrl);

            System.Console.Error.WriteLine("Configuring gRPC logging...");
            GrpcEnvironment.SetLogger(new GrpcLogger());

            System.Console.Error.WriteLine("Creating gRPC server...");
            var server = new Srv
            {
                Services =
                {
                    MenuEntries.BindService(kernel.Get <MenuEntriesImpl>()),
                    ToolbarEntries.BindService(kernel.Get <ToolbarEntriesImpl>())
                },
                Ports = { new ServerPort("localhost", 0, ServerCredentials.Insecure) }
            };

            server.Start();

            var serverUrl = "localhost:" + server.Ports.Select(x => x.BoundPort).First();

            System.Console.Error.WriteLine("gRPC server started on {0}", serverUrl);

            Console.WriteLine(serverUrl);
            Console.Error.WriteLine(serverUrl);

            var wantsUpdateSignal = kernel.GetAll <IWantsUpdateSignal>();

            while (true)
            {
                if (wantsUpdateSignal != null)
                {
                    foreach (var s in wantsUpdateSignal)
                    {
                        s.Update();
                    }
                }

                Thread.Sleep(16);
            }

            return(0);
        }
Ejemplo n.º 27
0
        public static int RealMain(string[] args)
        {
            int?trackProcessId = null;

            Console.Error.WriteLine("GameHost RealMain called with: " + args.Aggregate((a, b) => a + " " + b));
            var    argsList     = new Queue <string>(args);
            string editorUrl    = null;
            string assemblyFile = null;

            while (argsList.Count > 0)
            {
                var arg = argsList.Dequeue();
                switch (arg)
                {
                case "--trace":
                {
                    var pid     = argsList.Dequeue();
                    var process = Process.GetProcessById(int.Parse(pid));
                    process.Exited += (sender, e) =>
                    {
                        Console.Error.WriteLine("Parent process " + pid + " has exited, closing game host process.");
                        Environment.Exit(0);
                    };
                    process.EnableRaisingEvents = true;
                    if (process.HasExited)
                    {
                        Console.Error.WriteLine("Parent process " + pid + " has exited, closing game host process.");
                        Environment.Exit(0);
                    }
                    break;
                }

                case "--debug":
                    Debugger.Launch();
                    break;

                case "--editor-url":
                    editorUrl = argsList.Dequeue();
                    break;

                case "--assembly-path":
                    assemblyFile = argsList.Dequeue();
                    break;
                }
            }

            AppDomain.CurrentDomain.UnhandledException += (sender, e) =>
            {
                Console.Error.WriteLine(e.ExceptionObject);
            };

            if (editorUrl == null || assemblyFile == null)
            {
                System.Console.Error.WriteLine("Editor URL or assembly file not specified");
                return(1);
            }

            System.Console.Error.WriteLine("Starting game host...");
            System.Console.Error.WriteLine("Editor URL is: {0}", editorUrl);
            System.Console.Error.WriteLine("Assembly path is: {0}", assemblyFile);

            System.Console.Error.WriteLine("Configuring kernel...");

            var kernel = new StandardKernel();

            kernel.Bind <IEditorClientProvider>().To <EditorClientProvider>().InSingletonScope();
            kernel.Bind <IProjectManager>().To <ProjectManager>().InSingletonScope();
            kernel.Bind <IWantsUpdateSignal>().To <ProjectManagerUpdateSignal>().InSingletonScope();
            kernel.Bind <IWantsUpdateSignal>().To <PresenceCheckerUpdateSignal>().InSingletonScope();
            kernel.Bind <Api.Version1.Core.IConsoleHandle>().To <ConsoleHandle>().InSingletonScope();
            kernel.Bind <IGameRunner>().To <HostedGameRunner>().InSingletonScope();
            kernel.Bind <HostedEventEngineHook>().To <HostedEventEngineHook>().InSingletonScope();
            kernel.Bind <ISharedRendererClientFactory>().ToFactory();

            System.Console.Error.WriteLine("Configuring editor client provider with URL: {0}", editorUrl);
            var editorClientProvider = kernel.Get <IEditorClientProvider>();

            editorClientProvider.CreateChannel(editorUrl);

            // Load the target assembly.
            System.Console.Error.WriteLine("Loading game assembly from " + assemblyFile + "...");
            var assembly = Assembly.LoadFrom(assemblyFile);

            System.Console.Error.WriteLine("Constructing standard kernel...");
            kernel.Bind <IRawLaunchArguments>()
            .ToMethod(x => new DefaultRawLaunchArguments(new string[0]))
            .InSingletonScope();

            // Bind our extension hook first so that it runs before everything else.
            kernel.Bind <IEngineHook>().To <ExtensionEngineHook>().InSingletonScope();

            Func <System.Reflection.Assembly, Type[]> TryGetTypes = a =>
            {
                try
                {
                    return(a.GetTypes());
                }
                catch
                {
                    return(new Type[0]);
                }
            };

            System.Console.Error.WriteLine("Finding configuration classes in " + assemblyFile + "...");
            var typeSource = new List <Type>();

            foreach (var attribute in assembly.GetCustomAttributes(false))
            {
                if (attribute.GetType().FullName == "Protogame.ConfigurationAttribute")
                {
                    typeSource.Add(((ConfigurationAttribute)attribute).GameConfigurationOrServerClass);
                }
            }

            if (typeSource.Count == 0)
            {
                // Scan all types to find implementors of IGameConfiguration
                typeSource.AddRange(from type in TryGetTypes(assembly)
                                    select type);
            }

            System.Console.Error.WriteLine("Found {0} configuration classes in " + assemblyFile, typeSource.Count);

            System.Console.Error.WriteLine("Constructing game configurations...");
            var gameConfigurations = new List <IGameConfiguration>();

            foreach (var type in typeSource)
            {
                if (typeof(IGameConfiguration).IsAssignableFrom(type) &&
                    !type.IsInterface && !type.IsAbstract)
                {
                    gameConfigurations.Add(Activator.CreateInstance(type) as IGameConfiguration);
                }
            }

            ICoreGame game = null;
            var       hasBoundNewEventEngine = false;

            System.Console.Error.WriteLine("Configuring kernel and constructing game instance ({0} configurations)...", gameConfigurations.Count);
            foreach (var configuration in gameConfigurations)
            {
                System.Console.Error.WriteLine("Configuring with {0}...", configuration.GetType().FullName);

                configuration.ConfigureKernel(kernel);

                // Rebind services so the game renders correctly inside the editor.
                kernel.Rebind <IBaseDirectory>().To <HostedBaseDirectory>().InSingletonScope();
                kernel.Rebind <IBackBufferDimensions>().To <HostedBackBufferDimensions>().InSingletonScope();
                kernel.Rebind <IDebugRenderer>().To <DefaultDebugRenderer>().InSingletonScope();
                var bindings = kernel.GetCopyOfBindings();
                var mustBindNewEventEngine = false;
                if (bindings.ContainsKey(typeof(IEngineHook)))
                {
                    if (bindings[typeof(IEngineHook)].Any(x => x.Target == typeof(EventEngineHook)))
                    {
                        mustBindNewEventEngine = !hasBoundNewEventEngine;
                        kernel.UnbindSpecific <IEngineHook>(x => x.Target == typeof(EventEngineHook));
                    }

                    if (mustBindNewEventEngine)
                    {
                        kernel.Bind <IEngineHook>().ToMethod(ctx =>
                        {
                            return(ctx.Kernel.Get <HostedEventEngineHook>(ctx.Parent));
                        }).InSingletonScope();
                    }
                }

                if (game == null)
                {
                    game = configuration.ConstructGame(kernel);
                }
            }

            if (game != null)
            {
                System.Console.Error.WriteLine("Game instance is {0}", game.GetType().FullName);
            }

            var runner = kernel.Get <IGameRunner>(new NamedConstructorArgument("game", game));

            System.Console.Error.WriteLine("Configuring gRPC logging...");
            GrpcEnvironment.SetLogger(new GrpcLogger());

            System.Console.Error.WriteLine("Creating gRPC server...");
            var server = new Srv
            {
                Services =
                {
                    GameHostServer.BindService(kernel.Get <GameHostServerImpl>())
                },
                Ports = { new ServerPort("localhost", 0, ServerCredentials.Insecure) }
            };

            server.Start();

            var serverUrl = "localhost:" + server.Ports.Select(x => x.BoundPort).First();

            System.Console.Error.WriteLine("gRPC server started on {0}", serverUrl);

            Console.WriteLine(serverUrl);
            Console.Error.WriteLine(serverUrl);

            System.Console.Error.WriteLine("LoadFromPath complete");

            runner.Run();

            return(0);
        }
Ejemplo n.º 28
0
        static async Task Main(string[] args)
        {
            const string GrpcHost = "localhost";

            Console.WriteLine("Server:::");

            //Environment.SetEnvironmentVariable("GRPC_VERBOSITY", "DEBUG");
            //Environment.SetEnvironmentVariable("GRPC_TRACE", "all");

            Environment.SetEnvironmentVariable("SETTINGS_MAX_HEADER_LIST_SIZE", "1000000");

            GrpcEnvironment.SetLogger(new ConsoleLogger());

            var service = MagicOnionEngine.BuildServerServiceDefinition(new MagicOnionOptions(true)
            {
                // MagicOnionLogger = new MagicOnionLogToGrpcLogger(),
                MagicOnionLogger = new MagicOnionLogToGrpcLoggerWithNamedDataDump(),
                GlobalFilters    = new MagicOnionFilterAttribute[]
                {
                },
                EnableCurrentContext   = true,
                DisableEmbeddedService = true,
            });

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

            server.Start();

            // test webhost

            // NuGet: Microsoft.AspNetCore.Server.Kestrel
            var webHost = new WebHostBuilder()
                          .ConfigureServices(collection =>
            {
                // Add MagicOnionServiceDefinition for reference from Startup.
                collection.Add(new ServiceDescriptor(typeof(MagicOnionServiceDefinition), service));
            })
                          .UseKestrel()
                          .UseStartup <Startup>()
                          .UseUrls("http://localhost:5432")
                          .Build();

            webHost.Run();

            Console.ReadLine();


            {
                var channel = new Channel("localhost:12345", ChannelCredentials.Insecure);
                var client  = StreamingHubClient.Connect <IChatHub, IMessageReceiver2>(channel, new Receiver());

                Console.WriteLine("Call to Server");
                await client.JoinAsync("me", "foo");

                await Task.WhenAll(
                    client.SendMessageAsync("a"),
                    client.SendMessageAsync("b"),
                    client.SendMessageAsync("c"),
                    client.SendMessageAsync("d"),
                    client.SendMessageAsync("e"));

                Console.WriteLine("OK to Send");
            }
        }