/// <summary> /// Creates a thread pool threads polling on a set of completions queues. /// </summary> /// <param name="environment">Environment.</param> /// <param name="poolSize">Pool size.</param> /// <param name="completionQueueCount">Completion queue count.</param> public GrpcThreadPool(GrpcEnvironment environment, int poolSize, int completionQueueCount) { this.environment = environment; this.poolSize = poolSize; this.completionQueueCount = completionQueueCount; GrpcPreconditions.CheckArgument(poolSize >= completionQueueCount, "Thread pool size cannot be smaller than the number of completion queues used."); }
public static void Main(string[] args) { using (Channel channel = new Channel("127.0.0.1", 23456, Credentials.Insecure)) { Math.IMathClient client = new Math.MathClient(channel); MathExamples.DivExample(client); MathExamples.DivAsyncExample(client).Wait(); MathExamples.FibExample(client).Wait(); MathExamples.SumExample(client).Wait(); MathExamples.DivManyExample(client).Wait(); MathExamples.DependendRequestsExample(client).Wait(); } GrpcEnvironment.Shutdown(); }
public void Init() { GrpcEnvironment.Initialize(); server = new Server(); server.AddServiceDefinition(MathGrpc.BindService(new MathServiceImpl())); int port = server.AddListeningPort(host + ":0"); server.Start(); channel = new Channel(host + ":" + port); // TODO: get rid of the custom header here once we have dedicated tests // for header support. var stubConfig = new StubConfiguration((headerBuilder) => { headerBuilder.Add(new Metadata.MetadataEntry("customHeader", "abcdef")); }); client = MathGrpc.NewStub(channel, stubConfig); }
public static async Task Run(DelegateLogger dLogger) { //GrpcEnvironment.SetLogger(new Grpc.Core.Logging.ConsoleLogger()); GrpcEnvironment.SetLogger(new CompositeLogger( new DebugConsoleLogger(), dLogger)); tokenSource = new CancellationTokenSource(); using var ihost = await MagicOnionHost.CreateDefaultBuilder() .UseMagicOnion( new MagicOnionOptions(isReturnExceptionStackTraceInErrorDetail: true), new ServerPort("0.0.0.0", 12345, ServerCredentials.Insecure)) //.UseConsoleLifetime() .StartAsync(tokenSource.Token); host = ihost; await ihost.WaitForShutdownAsync(); }
public static IServiceProvider UseMagicOnion(this IServiceProvider services) { var loggerFactory = services.GetService <ILoggerFactory>(); GrpcEnvironment.SetLogger(new GrpcNetCoreLogger(loggerFactory)); // add using Microsoft.Extensions.Hosting; var appLifetime = (services ?? throw new ArgumentNullException(nameof(services))).GetRequiredService <IApplicationLifetime>(); var channel = services.GetRequiredService <Channel>(); _ = channel.ConnectAsync(); appLifetime.ApplicationStopping.Register(() => { channel.ShutdownAsync().GetAwaiter().GetResult(); }); return(services); }
public Shim( IOptions <ChaincodeSettings> chaincodeSettings, ILogger <Shim> logger, IHandlerFactory handlerFactory ) { if (chaincodeSettings == null) { throw new ArgumentNullException(nameof(chaincodeSettings)); } _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _handlerFactory = handlerFactory ?? throw new ArgumentNullException(nameof(handlerFactory)); _chaincodeSettings = chaincodeSettings.Value; if (_chaincodeSettings.LogGrpc) { GrpcEnvironment.SetLogger(new ConsoleLogger()); } }
public async Task HandleCall(ServerRpcNew newRpc, GrpcEnvironment environment) { var asyncCall = new AsyncCallServer <TRequest, TResponse>( method.ResponseMarshaller.Serializer, method.RequestMarshaller.Deserializer, environment, newRpc.Server); asyncCall.Initialize(newRpc.Call); var finishedTask = asyncCall.ServerSideCallAsync(); var requestStream = new ServerRequestStream <TRequest, TResponse>(asyncCall); var responseStream = new ServerResponseStream <TRequest, TResponse>(asyncCall); Status status; var context = HandlerUtils.NewContext(newRpc, asyncCall.Peer, responseStream, asyncCall.CancellationToken); try { Preconditions.CheckArgument(await requestStream.MoveNext().ConfigureAwait(false)); var request = requestStream.Current; // TODO(jtattermusch): we need to read the full stream so that native callhandle gets deallocated. Preconditions.CheckArgument(!await requestStream.MoveNext().ConfigureAwait(false)); var result = await handler(request, context).ConfigureAwait(false); status = context.Status; await responseStream.WriteAsync(result).ConfigureAwait(false); } catch (Exception e) { Logger.Error(e, "Exception occured in handler."); status = HandlerUtils.StatusFromException(e); } try { await responseStream.WriteStatusAsync(status, context.ResponseTrailers).ConfigureAwait(false); } catch (OperationCanceledException) { // Call has been already cancelled. } await finishedTask.ConfigureAwait(false); }
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 MagicOnionLogToGrpcLoggerWithDataDump(), GlobalFilters = new MagicOnionFilterAttribute[] { new MagicOnion.Server.EmbeddedFilters.ErrorDetailToTrailersFilterAttribute() } }); 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() .UseStartup <Startup>() .UseUrls(Configuration.GatewayHost) .Build(); webHost.Run(); }
public async Task ShouldUseAccessTokenSupplier() { // given GrpcEnvironment.SetLogger(new ConsoleLogger()); var keyCertificatePairs = new List <KeyCertificatePair>(); var serverCert = File.ReadAllText(ServerCertPath); keyCertificatePairs.Add(new KeyCertificatePair(serverCert, File.ReadAllText(ServerKeyPath))); var channelCredentials = new SslServerCredentials(keyCertificatePairs); var server = new Server(); server.Ports.Add(new ServerPort("0.0.0.0", 26505, channelCredentials)); var testService = new GatewayTestService(); var serviceDefinition = Gateway.BindService(testService); server.Services.Add(serviceDefinition); server.Start(); // client var accessTokenSupplier = new SimpleAccessTokenSupplier(); var zeebeClient = ZeebeClient.Builder() .UseGatewayAddress("0.0.0.0:26505") .UseTransportEncryption(ClientCertPath) .UseAccessTokenSupplier(accessTokenSupplier) .Build(); // when await zeebeClient.TopologyRequest().Send(); await zeebeClient.TopologyRequest().Send(); var topology = await zeebeClient.TopologyRequest().Send(); // then Assert.NotNull(topology); Assert.AreEqual(3, accessTokenSupplier.Count); }
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(); }
public static void Main(string[] args) { string host = "0.0.0.0"; GrpcEnvironment.Initialize(); Server server = new Server(); server.AddServiceDefinition(MathGrpc.BindService(new MathServiceImpl())); int port = server.AddListeningPort(host + ":23456"); 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(); }
public void Cleanup() { try { metadata?.Dispose(); metadata = null; call?.Dispose(); call = null; if (environment != null) { environment = null; // cleanup seems... unreliable on CLR // GrpcEnvironment.ReleaseAsync().Wait(1000); } } catch (Exception ex) { Console.Error.WriteLine(ex.Message); } }
public async Task HandleCall(ServerRpcNew newRpc, GrpcEnvironment environment) { var asyncCall = new AsyncCallServer <TRequest, TResponse>( method.ResponseMarshaller.Serializer, method.RequestMarshaller.Deserializer, environment, newRpc.Server); asyncCall.Initialize(newRpc.Call); var finishedTask = asyncCall.ServerSideCallAsync(); var requestStream = new ServerRequestStream <TRequest, TResponse>(asyncCall); var responseStream = new ServerResponseStream <TRequest, TResponse>(asyncCall); Status status; var context = HandlerUtils.NewContext(newRpc, asyncCall.Peer, responseStream, asyncCall.CancellationToken); try { await handler(requestStream, responseStream, context).ConfigureAwait(false); status = context.Status; } catch (Exception e) { if (!(e is RpcException)) { Logger.Warning(e, "Exception occured in handler."); } status = HandlerUtils.StatusFromException(e); } try { await asyncCall.SendStatusFromServerAsync(status, context.ResponseTrailers, null).ConfigureAwait(false); } catch (Exception) { asyncCall.Cancel(); throw; } await finishedTask.ConfigureAwait(false); }
private void Run() { GrpcEnvironment.Initialize(); Credentials credentials = null; if (options.useTls) { credentials = TestCredentials.CreateTestClientCredentials(options.useTestCa); } List <ChannelOption> channelOptions = null; if (!string.IsNullOrEmpty(options.serverHostOverride)) { channelOptions = new List <ChannelOption> { new ChannelOption(ChannelOptions.SslTargetNameOverride, options.serverHostOverride) }; } using (Channel channel = new Channel(options.serverHost, options.serverPort.Value, credentials, channelOptions)) { var stubConfig = StubConfiguration.Default; if (options.testCase == "service_account_creds" || options.testCase == "compute_engine_creds") { var credential = GoogleCredential.GetApplicationDefault(); if (credential.IsCreateScopedRequired) { credential = credential.CreateScoped(new[] { AuthScope }); } stubConfig = new StubConfiguration(OAuth2InterceptorFactory.Create(credential)); } TestService.ITestServiceClient client = new TestService.TestServiceClient(channel, stubConfig); RunTestCase(options.testCase, client); } GrpcEnvironment.Shutdown(); }
public async Task HandleCall(string methodName, CallSafeHandle call, GrpcEnvironment environment) { var asyncCall = new AsyncCallServer <TRequest, TResponse>( method.ResponseMarshaller.Serializer, method.RequestMarshaller.Deserializer, environment); asyncCall.Initialize(call); var finishedTask = asyncCall.ServerSideCallAsync(); var requestStream = new ServerRequestStream <TRequest, TResponse>(asyncCall); var responseStream = new ServerResponseStream <TRequest, TResponse>(asyncCall); Status status = Status.DefaultSuccess; try { Preconditions.CheckArgument(await requestStream.MoveNext()); var request = requestStream.Current; // TODO(jtattermusch): we need to read the full stream so that native callhandle gets deallocated. Preconditions.CheckArgument(!await requestStream.MoveNext()); var context = new ServerCallContext(); // TODO(jtattermusch): initialize the context var result = await handler(context, request); await responseStream.WriteAsync(result); } catch (Exception e) { Console.WriteLine("Exception occured in handler: " + e); status = HandlerUtils.StatusFromException(e); } try { await responseStream.WriteStatusAsync(status); } catch (OperationCanceledException) { // Call has been already cancelled. } await finishedTask; }
public static void Main(string[] args) { GrpcEnvironment.Initialize(); using (Channel channel = new Channel("127.0.0.1:23456")) { MathGrpc.IMathServiceClient stub = new MathGrpc.MathServiceClientStub(channel); MathExamples.DivExample(stub); MathExamples.DivAsyncExample(stub).Wait(); MathExamples.FibExample(stub).Wait(); MathExamples.SumExample(stub).Wait(); MathExamples.DivManyExample(stub).Wait(); MathExamples.DependendRequestsExample(stub).Wait(); } GrpcEnvironment.Shutdown(); }
public void Start() { GrpcEnvironment.SetLogger(this._logger); Server server = new Server { Ports = { new ServerPort(this._host, this._port, ServerCredentials.Insecure) } }; foreach (var service in this._serverServiceDefinitionList) { server.Services.Add(service); } server.Start(); Console.WriteLine("服务监听端口: " + this._port); Console.WriteLine("任意键退出..."); Console.Read(); server.ShutdownAsync().Wait(); }
public static void Main(string[] args) { if (args.Length != 2) { var message = $"Driver client launcher takes a two arguments. Found {args}"; Log.Log(Level.Error, message); throw new ArgumentException(message); } else { Log.Log(Level.Info, "Launching driver client with driver service port {0} config file {1}", args[0], args[1]); } GrpcEnvironment.SetLogger(new ConsoleLogger()); Log.Log(Level.Info, "Path of executing assembly{0}", ClientUtilities.GetPathToExecutingAssembly()); var launcher = TangFactory.GetTang().NewInjector().GetInstance <DriverLauncher>(); var driverClientConfig = launcher.GetDriverClientConfiguration(args[0], args[1]); var clock = TangFactory.GetTang().NewInjector(driverClientConfig).GetInstance <IClock>(); clock.Run(); Log.Log(Level.Info, "Driver client clock exit."); }
public async Task ShouldUseTransportEncryptionWithServerCert() { // given GrpcEnvironment.SetLogger(new ConsoleLogger()); var keyCertificatePairs = new List <KeyCertificatePair>(); var serverCert = File.ReadAllText(ServerCertPath); keyCertificatePairs.Add(new KeyCertificatePair(serverCert, File.ReadAllText(ServerKeyPath))); var channelCredentials = new SslServerCredentials(keyCertificatePairs); var server = new Server(); server.Ports.Add(new ServerPort("0.0.0.0", 26505, channelCredentials)); var testService = new GatewayTestService(); var serviceDefinition = Gateway.BindService(testService); server.Services.Add(serviceDefinition); server.Start(); // client var zeebeClient = ZeebeClient.Builder() .UseGatewayAddress("0.0.0.0:26505") .UseTransportEncryption(ServerCertPath) .Build(); // when var publishMessageResponse = await zeebeClient .NewPublishMessageCommand() .MessageName("messageName") .CorrelationKey("p-1") .Send(); // then Assert.NotNull(publishMessageResponse); }
public void Init() { // TODO(https://github.com/grpc/grpc/issues/14963): on linux, setting // these environment variables might not actually have any affect. // This is OK because we only really care about running this test on // Windows, however, a fix made for $14963 should be applied here. Environment.SetEnvironmentVariable("GRPC_TRACE", "all"); Environment.SetEnvironmentVariable("GRPC_VERBOSITY", "DEBUG"); newLogger = new SocketUsingLogger(GrpcEnvironment.Logger); GrpcEnvironment.SetLogger(newLogger); // Disable SO_REUSEPORT to prevent https://github.com/grpc/grpc/issues/10755 server = new Server(new[] { new ChannelOption(ChannelOptions.SoReuseport, 0) }) { Services = { TestService.BindService(new TestServiceImpl()) }, Ports = { { "[::1]", ServerPort.PickUnused, ServerCredentials.Insecure } } }; server.Start(); int port = server.Ports.Single().BoundPort; channel = new Channel("loopback6.unittest.grpc.io", port, ChannelCredentials.Insecure); client = new TestService.TestServiceClient(channel); }
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(); }
public override void Start() { AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2Support", true); GrpcEnvironment.SetLogger(new UnityLogger()); Converter?.SetInitTRS(Vector3.zero, Quaternion.identity); var servicesChain = new IChainable <MapsManagerPb.MapsManagerPbBase>[] { new PointsMapManager(_containerTree.Points, Converter), new ObservationsMapManager(_containerTree.Observations, Converter), new TrackedObjsMapManager(_containerTree.TrackedObjs, Converter), new LinesMapManager(_containerTree.Lines, Converter), new InfinitePlanesMapManager(_containerTree.InfinitePlanes, Converter) }.BuildChain(); _containerTree.DisplayName = $"From gRPC at port {TypedSettings.Port}"; #if UNITY_EDITOR || UNITY_STANDALONE Debug.Log($"{TypedSettings.IPAddress}:{TypedSettings.Port}"); #endif _server = new GrpcServer() { Services = { MapsManagerPb.BindService(servicesChain), SceneManagerPb.BindService(new SceneManager(_containerTree)), ImageManagerPb.BindService(new ImageManager((RawImagePresenter)_containerTree.Image)) }, Ports = { new ServerPort("0.0.0.0", TypedSettings.Port, ServerCredentials.Insecure), }, }; StartServer(); }
public StartupShutdownBase Create() { var cacheConfig = _arguments.Configuration; cacheConfig.LocalCasSettings = cacheConfig.LocalCasSettings.FilterUnsupportedNamedCaches(_arguments.HostInfo.Capabilities, _logger); var distributedSettings = cacheConfig.DistributedContentSettings; var isLocal = distributedSettings == null || !distributedSettings.IsDistributedContentEnabled; var serviceConfiguration = CreateServiceConfiguration( _logger, _fileSystem, cacheConfig.LocalCasSettings, distributedSettings, new AbsolutePath(_arguments.DataRootPath), isDistributed: !isLocal); var localServerConfiguration = CreateLocalServerConfiguration(cacheConfig.LocalCasSettings.ServiceSettings, serviceConfiguration, distributedSettings); // Initialization of the GrpcEnvironment is nasty business: we have a wrapper class around the internal // state. The internal state has a flag inside that marks whether it's been initialized or not. If we do // any Grpc activity, the internal state will be initialized, and all further attempts to change things // will throw. Since we may need to initialize a Grpc client before we do a Grpc server, this means we // need to call this early, even if it doesn't have anything to do with what's going on here. GrpcEnvironment.InitializeIfNeeded(localServerConfiguration.GrpcThreadPoolSize ?? 70); if (isLocal) { // In practice, we don't really pass in a null distributedSettings. Hence, we'll enable the metadata // store whenever its set to true. This can only happen in the Application verb, because the Service // verb doesn't change the defaults. return(CreateLocalServer(localServerConfiguration, distributedSettings)); } else { return(CreateDistributedServer(localServerConfiguration, distributedSettings)); } }
static void Main(string[] args) { // GrpcのLogging機構を使う GrpcEnvironment.SetLogger(new ConsoleLogger()); GrpcEnvironment.Logger.Info("Server startup! ================================="); // MaginOnion側のログを gRPC のログに流し込む設定 // ※JSON形式でデータダンプする var logger = new MagicOnionLogToGrpcLoggerWithDataDump(); var options = new MagicOnionOptions(true) { MagicOnionLogger = logger }; //--- ここで動的にアセンブリを解釈し、通信されてきたデータと API 本体とのマップを作る var service = MagicOnionEngine.BuildServerServiceDefinition(options); //--- API を公開する IP / Port / 認証情報などを決定し、gRPC サーバーを起動 var port = new ServerPort("localhost", 12345, ServerCredentials.Insecure); var server = new Server(new[] { new ChannelOption(ChannelOptions.MaxReceiveMessageLength, int.MaxValue), new ChannelOption(ChannelOptions.MaxSendMessageLength, int.MaxValue), }) { Services = { service }, Ports = { port }, }; server.Start(); GrpcEnvironment.Logger.Info("Server started"); //--- exe が終了しちゃわないように Console.ReadLine(); GrpcEnvironment.Logger.Info("Server closed. ---------------------------------"); }
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(); }
public async Task HandleCall(ServerRpcNew newRpc, GrpcEnvironment environment) { var asyncCall = new AsyncCallServer <TRequest, TResponse>( method.ResponseMarshaller.Serializer, method.RequestMarshaller.Deserializer, environment, newRpc.Server); asyncCall.Initialize(newRpc.Call); var finishedTask = asyncCall.ServerSideCallAsync(); var requestStream = new ServerRequestStream <TRequest, TResponse>(asyncCall); var responseStream = new ServerResponseStream <TRequest, TResponse>(asyncCall); Status status; var context = HandlerUtils.NewContext(newRpc, asyncCall.Peer, responseStream, asyncCall.CancellationToken); try { await handler(requestStream, responseStream, context).ConfigureAwait(false); status = context.Status; } catch (Exception e) { Logger.Error(e, "Exception occured in handler."); status = HandlerUtils.StatusFromException(e); } try { await responseStream.WriteStatusAsync(status, context.ResponseTrailers).ConfigureAwait(false); } catch (OperationCanceledException) { // Call has been already cancelled. } await finishedTask.ConfigureAwait(false); }
private void Run() { var server = new Server(); server.AddServiceDefinition(TestService.BindService(new TestServiceImpl())); string host = "0.0.0.0"; int port = options.port.Value; if (options.useTls) { server.AddListeningPort(host, port, TestCredentials.CreateTestServerCredentials()); } else { server.AddListeningPort(host, options.port.Value); } Console.WriteLine("Running server on " + string.Format("{0}:{1}", host, port)); server.Start(); server.ShutdownTask.Wait(); GrpcEnvironment.Shutdown(); }
public static int Main(string[] args) { // Make logger immune to NUnit capturing stdout and stderr to workaround https://github.com/nunit/nunit/issues/1406. GrpcEnvironment.SetLogger(new ConsoleLogger()); return(new AutoRun(typeof(NUnitMain).GetTypeInfo().Assembly).Execute(args)); }
protected override bool ReleaseHandle() { Native.grpcsharp_server_destroy(handle); GrpcEnvironment.GrpcNativeShutdown(); return(true); }
public CompletionRegistry(GrpcEnvironment environment) { this.environment = environment; }
public void ShutdownAndNotify(BatchCompletionDelegate callback, GrpcEnvironment environment) { var ctx = BatchContextSafeHandle.Create(); environment.CompletionRegistry.RegisterBatchCompletion(ctx, callback); grpcsharp_server_shutdown_and_notify_callback(this, environment.CompletionQueue, ctx); }
public void RequestCall(BatchCompletionDelegate callback, GrpcEnvironment environment) { var ctx = BatchContextSafeHandle.Create(); environment.CompletionRegistry.RegisterBatchCompletion(ctx, callback); grpcsharp_server_request_call(this, environment.CompletionQueue, ctx).CheckOk(); }
public GrpcThreadPool(GrpcEnvironment environment, int poolSize) { this.environment = environment; this.poolSize = poolSize; }
IntPtr lastRegisteredKey; // only for testing public CompletionRegistry(GrpcEnvironment environment, Func <BatchContextSafeHandle> batchContextFactory) { this.environment = GrpcPreconditions.CheckNotNull(environment); this.batchContextFactory = GrpcPreconditions.CheckNotNull(batchContextFactory); }
private static IReadOnlyCollection<CompletionQueueSafeHandle> CreateCompletionQueueList(GrpcEnvironment environment, int completionQueueCount) { var list = new List<CompletionQueueSafeHandle>(); for (int i = 0; i < completionQueueCount; i++) { var completionRegistry = new CompletionRegistry(environment); list.Add(CompletionQueueSafeHandle.Create(completionRegistry)); } return list.AsReadOnly(); }
/// <summary> /// Main /// </summary> /// <param name="args">参数</param> public static void Main(string[] args) { Environment.SetEnvironmentVariable("SETTINGS_MAX_HEADER_LIST_SIZE", "1000000"); GrpcEnvironment.SetLogger(new ConsoleLogger()); var options = new MagicOnionOptions(true) { MagicOnionLogger = new MagicOnionLogToGrpcLoggerWithNamedDataDump(), GlobalFilters = new MagicOnionFilterAttribute[] { }, EnableCurrentContext = true }; var service = MagicOnionEngine.BuildServerServiceDefinition(new Assembly[] { typeof(MyCalculateService).Assembly }, options); var server = new Grpc.Core.Server() { Services = { service }, Ports = { new ServerPort("192.168.2.22", 5001, ServerCredentials.Insecure) }, }; server.Start(); CreateWebHostBuilder(service, args).Build().Run(); }