public async static Task Main(string[] args) { await Task.Delay(TimeSpan.FromSeconds(2)); // This switch must be set before creating the GrpcChannel/HttpClient. AppContext.SetSwitch( "System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); var options = new GrpcChannelOptions { Credentials = ChannelCredentials.Insecure }; using var channel = GrpcChannel.ForAddress("http://localhost:5000", options); var client = new GrpcDemo.Greeter.GreeterClient(channel); // make a call using (var call = client.SayHello(new HelloRequest())) { while (await call.ResponseStream.MoveNext()) { var reply = call.ResponseStream.Current; Console.WriteLine("Received " + reply.ToString()); } } channel.ShutdownAsync().Wait(); }
static async Task Main(string[] args) { AppContext.SetSwitch( "System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); GrpcChannelOptions o = new GrpcChannelOptions(); var h = new HostBuilder() .ConfigureServices((context, services) => { //var ssl = new SslCredentials(PublicKey); //var options = new List<ChannelOption>(); //options.Add(new ChannelOption(ChannelOptions.SslTargetNameOverride, "CTCRootCA")); //var channel = new Channel("localhost", 50001, ssl, options); //var channel = new Channel("localhost", 60001, ssl); //var channel = new Channel("localhost", 50001, new SslCredentials()); services.AddNetRpcGrpcClient(i => { i.Url = "http://localhost:5000"; i.ChannelOptions.MaxReceiveMessageSize = 20 * 1024 * 1024; // 2 MB i.ChannelOptions.MaxSendMessageSize = 20 * 1024 * 1024; // 5 MB }); services.AddNetRpcClientContract <IService>(); services.AddHostedService <MyHost>(); }) .Build(); await h.RunAsync(); }
public static void Main() { Thread.Sleep(TimeSpan.FromSeconds(2)); // wait for server to wake up var channelOptions = new GrpcChannelOptions() { HttpClient = CreateGrpcHttpClient(acceptSelfSignedCertificate: true) }; var channel = GrpcChannel.ForAddress("https://grpc-reverseproxy-lb-nginx:443", channelOptions); var client = new Greeter.GreeterClient(channel); var user = "******"; for (int i = 0; i < 10000; i++) { try { var reply = client.SayHello(new HelloRequest { Name = user }); Console.WriteLine("Greeting: " + reply.Message); } catch (RpcException e) { Console.WriteLine("Error invoking: " + e.Status); } Thread.Sleep(1000); } channel.ShutdownAsync().Wait(); }
public GrpcReportsTransport(IOptions <GrpcReportsTransportOptions> options, ILogger <GrpcReportsTransport> logger) { Options = options.Value ?? throw new ArgumentNullException(); HttpClient httpClient = null; if (Options.NeedHttpClientFunc != null) { httpClient = Options.NeedHttpClientFunc(); } else if (Options.AllowAnyRemoteCertificate) { var httpClientHandler = new HttpClientHandler { ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator }; httpClient = new HttpClient(httpClientHandler); } var grpcChannelOptions = new GrpcChannelOptions { HttpClient = httpClient }; if (Options.PostConfigGrpcChannelOptions != null) { Options.PostConfigGrpcChannelOptions(grpcChannelOptions); } var channel = GrpcChannel.ForAddress(Options.CollectorAddress, grpcChannelOptions); _client = new GrpcCollector.GrpcCollectorClient(channel); _RequestCollection = new AsyncCallbackDeferFlushCollection <RequestInfoWithDetail>(Push, 50, 5); _logger = logger; }
public Key(string endpoint, GrpcChannelOptions options, ApiConfig config, GrpcAdapter adapter) { Endpoint = endpoint; Options = options; Config = config; GrpcAdapter = adapter; }
public VoiceKitClient(string apiKey, string secretKey) { // _authSTT = GenerateToken(secretKey, apiKey); _authSTT = new Auth(apiKey, secretKey, "tinkoff.cloud.stt"); GrpcChannelOptions gco = new GrpcChannelOptions(); //var cred = new SslCredentials(); gco.Credentials = new SslCredentials(); // var channelSTT = new Channel("stt.tinkoff.ru:443", cred); var channelSTT = GrpcChannel.ForAddress("https://stt.tinkoff.ru:443", gco); // var channelSTT = new Grpc.Core.Channel("stt.tinkoff.ru:443", cred); _clientSTT = new SpeechToText.SpeechToTextClient(channelSTT); }
/// <summary> /// Returns a call invoker from this pool, creating a new one if there is no call invoker /// already associated with <paramref name="endpoint"/> and <paramref name="options"/>. /// </summary> /// <param name="endpoint">The endpoint to connect to. Must not be null.</param> /// <param name="options"> /// The options to use for each channel created by the call invoker, possibly including the special /// <see cref="GcpCallInvoker.ApiConfigChannelArg">GcpCallInvoker.ApiConfigChannelArg</see> option to /// control the <see cref="GcpCallInvoker"/> behavior itself. /// </param> /// <returns>A call invoker for the specified endpoint.</returns> public GcpCallInvoker GetCallInvoker(string endpoint, GrpcChannelOptions options = null) { GaxPreconditions.CheckNotNull(endpoint, nameof(endpoint)); var credentials = _credentialsCache.GetCredentials(); return(GetCallInvoker(endpoint, options, credentials)); }
public static async Task Main() { var options = new GrpcChannelOptions(); var channel = GrpcChannel.ForAddress("https://localhost:5001", options); var client = new FooService.FooServiceClient(channel); ConsoleKey choice; while ((choice = ShowApplicationInformation()) != ConsoleKey.Escape) { if (choice == ConsoleKey.D1) { await RunUnaryRpc(client).ConfigureAwait(false); } else if (choice == ConsoleKey.D2) { await RunServerStreamingRpc(client).ConfigureAwait(false); } else if (choice == ConsoleKey.D3) { await RunClientStreamingRpc(client).ConfigureAwait(false); } else if (choice == ConsoleKey.D4) { await RunBidirectionalRpc(client).ConfigureAwait(false); } else { Console.WriteLine("Invalid option selected.\n"); } } }
public static void Main() { EnsureLoadAssembly.Load(); var channelOptions = new GrpcChannelOptions() { LoggerFactory = GetConsoleLoggerFactory(), HttpClient = CreateGrpcHttpClient(acceptSelfSignedCertificate: true), Attributes = new GrpcAttributes(new Dictionary <string, object>() { { GrpcAttributesLbConstants.DnsResolverOptions, GetDnsClientResolverPluginOptions() } }) }; var channelTarget = Environment.GetEnvironmentVariable("SERVICE_TARGET"); var channel = GrpcChannel.ForAddress(channelTarget, channelOptions); var client = new Greeter.GreeterClient(channel); var user = "******"; for (int i = 0; i < 10000; i++) { try { var reply = client.SayHello(new HelloRequest { Name = user }); Console.WriteLine("Greeting: " + reply.Message); } catch (RpcException e) { Console.WriteLine("Error invoking: " + e.Status); } Thread.Sleep(1000); } channel.ShutdownAsync().Wait(); Console.WriteLine(); }
public static HttpClientCallInvoker Create( HttpClient httpClient, ILoggerFactory?loggerFactory = null, ISystemClock?systemClock = null, Action <GrpcChannelOptions>?configure = null, bool?disableClientDeadline = null, long?maxTimerPeriod = null, IOperatingSystem?operatingSystem = null, ServiceConfig?serviceConfig = null) { var channelOptions = new GrpcChannelOptions { LoggerFactory = loggerFactory, HttpClient = httpClient, ServiceConfig = serviceConfig }; configure?.Invoke(channelOptions); var channel = GrpcChannel.ForAddress(httpClient.BaseAddress !, channelOptions); ConfigureChannel(systemClock, disableClientDeadline, maxTimerPeriod, operatingSystem, channel); return(new HttpClientCallInvoker(channel)); }
public void MaxReconnectBackoff_ManyBackoffs_MatchConfiguredBackoff() { // Arrange var services = new ServiceCollection(); services.AddSingleton <IRandomGenerator, TestRandomGenerator>(); var channelOptions = new GrpcChannelOptions { MaxReconnectBackoff = TimeSpan.FromSeconds(10), ServiceProvider = services.BuildServiceProvider() }; // Act var channel = GrpcChannel.ForAddress("https://localhost", channelOptions); var backoffPolicy = channel.ConnectionManager.BackoffPolicyFactory.Create(); // Assert for (var i = 0; i < 100; i++) { if (backoffPolicy.NextBackoff() == TimeSpan.FromMinutes(10)) { break; } } Assert.AreEqual(TimeSpan.FromSeconds(10), backoffPolicy.NextBackoff()); }
static async Task Main(string[] args) { AppContext.SetSwitch("System.Net.Http.UseSocketsHttpHandler", true); AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2Support", true); AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); try { var handler = new SocketsHttpHandler(); var httpClient = new HttpClient(handler); var options = new GrpcChannelOptions { HttpClient = httpClient, DisposeHttpClient = true }; var channel = GrpcChannel.ForAddress("https://ttsl.tech/", options); var client = new Weather.Weather.WeatherClient(channel); var weatherService = new GrpcWeatherForecastService(client); var result = await weatherService.GetWeather(); } catch (Exception e) { Console.WriteLine(e); throw; } }
public async Task State_ConnectAndDispose_StateChanges() { // Arrange var services = new ServiceCollection(); services.AddSingleton <ResolverFactory, ChannelTestResolverFactory>(); services.AddSingleton <ISubchannelTransportFactory, TestSubchannelTransportFactory>(); var handler = new TestHttpMessageHandler(); var channelOptions = new GrpcChannelOptions { ServiceProvider = services.BuildServiceProvider(), HttpHandler = handler }; // Act var channel = GrpcChannel.ForAddress("https://localhost", channelOptions); // Assert Assert.AreEqual(ConnectivityState.Idle, channel.State); await channel.ConnectAsync().DefaultTimeout(); Assert.AreEqual(ConnectivityState.Ready, channel.State); channel.Dispose(); Assert.AreEqual(ConnectivityState.Shutdown, channel.State); }
public void Resolver_DefaultPort_MatchesSecure(bool isSecure, int expectedPort) { // Arrange var services = new ServiceCollection(); services.AddSingleton <ResolverFactory, ChannelTestResolverFactory>(); services.AddSingleton <ISubchannelTransportFactory, TestSubchannelTransportFactory>(); var handler = new TestHttpMessageHandler(); var channelOptions = new GrpcChannelOptions { Credentials = isSecure ? ChannelCredentials.SecureSsl : ChannelCredentials.Insecure, ServiceProvider = services.BuildServiceProvider(), HttpHandler = handler }; // Act var channel = GrpcChannel.ForAddress("test:///localhost", channelOptions); // Assert Assert.IsInstanceOf(typeof(ChannelTestResolver), channel.ConnectionManager._resolver); var resolver = (ChannelTestResolver)channel.ConnectionManager._resolver; Assert.AreEqual(expectedPort, resolver.Options.DefaultPort); }
public static HttpClientCallInvoker Create( HttpClient httpClient, ILoggerFactory?loggerFactory = null, ISystemClock?systemClock = null, Action <GrpcChannelOptions>?configure = null, bool?disableClientDeadline = null, long?maxTimerPeriod = null, IOperatingSystem?operatingSystem = null) { var channelOptions = new GrpcChannelOptions { LoggerFactory = loggerFactory, HttpClient = httpClient }; configure?.Invoke(channelOptions); var channel = GrpcChannel.ForAddress(httpClient.BaseAddress !, channelOptions); channel.Clock = systemClock ?? SystemClock.Instance; if (disableClientDeadline != null) { channel.DisableClientDeadline = disableClientDeadline.Value; } if (maxTimerPeriod != null) { channel.MaxTimerDueTime = maxTimerPeriod.Value; } if (operatingSystem != null) { channel.OperatingSystem = operatingSystem; } return(new HttpClientCallInvoker(channel)); }
public Client(GrpcChannelOptions options, string url, string host, int port, string connectionDescription) { _channel = GrpcChannel.ForAddress(url !, options); Host = host; Port = port; ConnectionDescription = connectionDescription; }
public static HttpClientCallInvoker Create( HttpClient httpClient, ILoggerFactory?loggerFactory = null, ISystemClock?systemClock = null, Action <GrpcChannelOptions>?configure = null, bool?disableClientDeadlineTimer = null) { var channelOptions = new GrpcChannelOptions { LoggerFactory = loggerFactory, HttpClient = httpClient }; configure?.Invoke(channelOptions); var channel = GrpcChannel.ForAddress(httpClient.BaseAddress, channelOptions); channel.Clock = systemClock ?? SystemClock.Instance; if (disableClientDeadlineTimer != null) { channel.DisableClientDeadlineTimer = disableClientDeadlineTimer.Value; } return(new HttpClientCallInvoker(channel)); }
private static GrpcChannelOptions GetChannelOptions(HttpClient httpClient) { var options = new GrpcChannelOptions(); options.HttpClient = httpClient; return(options); }
/// <summary> /// Builds the common GRPC channel options for TLS 1.2 and HTTP/2 /// </summary> /// <param name="maximumConcurrentConnections">The maximum number of concurrent connections allowed to a host</param> /// <param name="remoteCertificateValidation">The remote certificate callback in use</param> /// <param name="webProxy">The web proxy in use if one is required</param> /// <param name="credentials">Credentials associated with the channel if provided</param> /// <returns>A populated channel options instance</returns> public static GrpcChannelOptions GetChannelOptions(int maximumConcurrentConnections, Func <HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> remoteCertificateValidation, IWebProxy webProxy = null, ChannelCredentials credentials = null) { Guard.NotLessThan(nameof(maximumConcurrentConnections), maximumConcurrentConnections, 1); Guard.NotNull(nameof(remoteCertificateValidation), remoteCertificateValidation); var handler = new HttpClientHandler { MaxConnectionsPerServer = maximumConcurrentConnections, SslProtocols = SslProtocols.Tls12, ServerCertificateCustomValidationCallback = remoteCertificateValidation }; if (webProxy != null) { handler.Proxy = webProxy; } GrpcChannelOptions options = new GrpcChannelOptions { Credentials = credentials, HttpHandler = handler }; return(options); }
public async Task <bool> IsSameOrder() { var grpcOption = new GrpcChannelOptions(); grpcOption.MaxReceiveMessageSize = 100 * 1024 * 1024; grpcOption.MaxSendMessageSize = 100 * 1024 * 1024; using var channel = GrpcChannel.ForAddress(_grpcUrl, grpcOption); var client = new checkOrder.checkOrderClient(channel); var request = new OrderRequest(); request.Name = "李白"; request.City = "北京"; request.OrderNumber = "AAAAAAA"; request.CreationTime = Google.Protobuf.WellKnownTypes.Timestamp.FromDateTime(DateTime.UtcNow); request.PackageList.Add(new PackageRequest { Weight = 1f, OrderNumber = "AAAAAA" }); var reply = await client.IsSameOrderAsync(request); return(reply.IsSame); }
public static void Main() { var channelOptions = new GrpcChannelOptions() { LoggerFactory = GetConsoleLoggerFactory(), HttpClient = CreateGrpcHttpClient(acceptSelfSignedCertificate: true), DefaultLoadBalancingPolicy = "round_robin" }; var channelTarget = Environment.GetEnvironmentVariable("SERVICE_TARGET"); var channel = GrpcChannel.ForAddress(channelTarget, channelOptions); var client = new Greeter.GreeterClient(channel); var user = "******"; for (int i = 0; i < 10000; i++) { try { var reply = client.SayHello(new HelloRequest { Name = user }); Console.WriteLine("Greeting: " + reply.Message); } catch (RpcException e) { Console.WriteLine("Error invoking: " + e.Status); } Thread.Sleep(1000); } channel.ShutdownAsync().Wait(); Console.WriteLine(); }
/// <summary> /// Asynchronously returns a call invoker from this pool, creating a new one if there is no call invoker /// already associated with <paramref name="endpoint"/> and <paramref name="options"/>. /// </summary> /// <param name="endpoint">The endpoint to connect to. Must not be null.</param> /// <param name="options"> /// The options to use for each channel created by the call invoker, possibly including the special /// <see cref="GcpCallInvoker.ApiConfigChannelArg">GcpCallInvoker.ApiConfigChannelArg</see> option to /// control the <see cref="GcpCallInvoker"/> behavior itself. /// </param> /// <returns>A task representing the asynchronous operation. The value of the completed /// task will be a call invoker for the specified endpoint.</returns> public async Task <GcpCallInvoker> GetCallInvokerAsync(string endpoint, GrpcChannelOptions options = null) { GaxPreconditions.CheckNotNull(endpoint, nameof(endpoint)); var credentials = await _credentialsCache.GetCredentialsAsync().ConfigureAwait(false); return(GetCallInvoker(endpoint, options, credentials)); }
public ServiceHostGrpcServiceFactory(IExecutionContextAccessor executionContextAccessor, IOptions <ServiceProxyApplicationOptions> options, ILoggerFactory?loggerFactory) { if (executionContextAccessor == null) { throw new ArgumentNullException(nameof(executionContextAccessor)); } if (options?.Value == null) { throw new ArgumentNullException(nameof(options)); } var baseUrl = options.Value.ServiceBaseUrl ?? throw new ArgumentException($"{nameof(ServiceProxyApplicationOptions.ServiceBaseUrl)} must be specified.", nameof(options)); var channelOptions = new GrpcChannelOptions { LoggerFactory = loggerFactory ?? NullLoggerFactory.Instance, // https://github.com/grpc/grpc-dotnet/issues/407#issuecomment-529705056 ThrowOperationCanceledOnCancellation = true }; _channel = GrpcChannel.ForAddress(baseUrl, channelOptions); _callInvoker = _channel.Intercept(new CaptureExecutionContextInterceptor(executionContextAccessor)); _clientFactory = ClientFactory.Create(ServiceHostContractSerializer.CreateBinderConfiguration()); }
private ChannelBase CreateSecureChannel() { var getEC2TagOption = configuration.GetEC2TagOptionFromEC2TagsSection(); var environmentTag = getEC2TagOption.Environment; var customerTag = getEC2TagOption.Customer; var jwtBearerTokenSymetricSecurityKey = refinitivTickPriceHistoryApiConfig.RefinitivTickPriceHistoryApiJwtBearerTokenSymetricSecurityKey; var credentials = CallCredentials.FromInterceptor((context, metadata) => { var jwtToken = new JwtToken() .SetExpires(DateTime.UtcNow.AddMinutes(2)) .SetIssuer(environmentTag, customerTag, PermissionScopeTypeConstants.TickPriceHistory) .SetAudience(environmentTag, customerTag, PermissionScopeTypeConstants.TickPriceHistory); var bearerToken = jwtTokenService.Generate(jwtToken, jwtBearerTokenSymetricSecurityKey); metadata.Add("Authorization", $"Bearer {bearerToken}"); return(Task.CompletedTask); }); var channelCredentials = ChannelCredentials.Create(new SslCredentials(), credentials); var grpcChannelOptions = new GrpcChannelOptions { //HttpClient = httpClient, // LoggerFactory = logFactory, Credentials = channelCredentials }; var channel = GrpcChannel.ForAddress(refinitivTickPriceHistoryApiConfig.RefinitivTickPriceHistoryApiAddress, grpcChannelOptions); return(channel); }
/// <summary> /// Builds a DaprClient. /// </summary> /// <returns>A DaprClient isntance.</returns> public DaprClient Build() { var uri = new Uri(this.daprEndpoint); if (uri.Scheme.Equals(Uri.UriSchemeHttp)) { // Set correct switch to make insecure gRPC service calls. This switch must be set before creating the GrpcChannel. AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); } else { // Workaround to allow with mTLS enabled Dapr grpc endpoint. The behavior will be fixed in 0.6.0 Dapr runtime. if (this.gRPCChannelOptions == null) { var httpClientHandler = new HttpClientHandler(); // validate server cert. httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, sslPolicyErrors) => { return(true); }; var httpClient = new HttpClient(httpClientHandler); this.gRPCChannelOptions = new GrpcChannelOptions { HttpClient = httpClient, DisposeHttpClient = true }; } } var channel = GrpcChannel.ForAddress(this.daprEndpoint, this.gRPCChannelOptions ?? new GrpcChannelOptions()); return(new DaprClientGrpc(channel, this.jsonSerializerOptions)); }
private CallInvoker CreateInvoker(EntryKey key) { var(name, type) = (key.Name, key.Type); var scope = _scopeFactory.CreateScope(); var services = scope.ServiceProvider; try { var httpClientFactoryOptions = _httpClientFactoryOptionsMonitor.Get(name); if (httpClientFactoryOptions.HttpClientActions.Count > 0) { throw new InvalidOperationException($"The ConfigureHttpClient method is not supported when creating gRPC clients. Unable to create client with name '{name}'."); } var clientFactoryOptions = _grpcClientFactoryOptionsMonitor.Get(name); var httpHandler = _messageHandlerFactory.CreateHandler(name); if (httpHandler == null) { throw new ArgumentNullException(nameof(httpHandler)); } var channelOptions = new GrpcChannelOptions(); channelOptions.HttpHandler = httpHandler; channelOptions.LoggerFactory = _loggerFactory; channelOptions.ServiceProvider = services; if (clientFactoryOptions.ChannelOptionsActions.Count > 0) { foreach (var applyOptions in clientFactoryOptions.ChannelOptionsActions) { applyOptions(channelOptions); } } var address = clientFactoryOptions.Address; if (address == null) { throw new InvalidOperationException($@"Could not resolve the address for gRPC client '{name}'. Set an address when registering the client: services.AddGrpcClient<{type.Name}>(o => o.Address = new Uri(""https://localhost:5001""))"); } var channel = GrpcChannel.ForAddress(address, channelOptions); var httpClientCallInvoker = channel.CreateCallInvoker(); var resolvedCallInvoker = GrpcClientFactoryOptions.BuildInterceptors( httpClientCallInvoker, services, clientFactoryOptions, InterceptorScope.Channel); return(resolvedCallInvoker); } catch { // If something fails while creating the handler, dispose the services. scope?.Dispose(); throw; } }
/// <summary> /// Returns a channel from this pool, creating a new one if there is no channel /// already associated with <paramref name="endpoint"/>. /// The specified channel options are applied, but only those options. /// </summary> /// <param name="grpcAdapter">The gRPC implementation to use. Must not be null.</param> /// <param name="endpoint">The endpoint to connect to. Must not be null.</param> /// <param name="channelOptions">The channel options to include. May be null.</param> /// <returns>A channel for the specified endpoint.</returns> internal ChannelBase GetChannel(GrpcAdapter grpcAdapter, string endpoint, GrpcChannelOptions channelOptions) { GaxPreconditions.CheckNotNull(grpcAdapter, nameof(grpcAdapter)); GaxPreconditions.CheckNotNull(endpoint, nameof(endpoint)); var credentials = _lazyScopedDefaultChannelCredentials.Value.ResultWithUnwrappedExceptions(); return(GetChannel(grpcAdapter, endpoint, channelOptions, credentials)); }
/// <summary> /// Initializes a new instance of the <see cref="ResolverOptions"/> class. /// </summary> internal ResolverOptions(Uri address, int defaultPort, ILoggerFactory loggerFactory, GrpcChannelOptions channelOptions) { Address = address; DefaultPort = defaultPort; DisableServiceConfig = channelOptions.DisableResolverServiceConfig; LoggerFactory = loggerFactory; ChannelOptions = channelOptions; }
public GuardadoDeArchivos() { GrpcChannelOptions grpcChannelOptions = new GrpcChannelOptions(); grpcChannelOptions.Credentials = ChannelCredentials.Insecure; AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); ServicioDeArchivos = GrpcChannel.ForAddress("http://172.17.0.6:80", grpcChannelOptions); }
public GrpcCoreClientFactory(string grpcServerAddress) { var opt = new GrpcChannelOptions() { Credentials = ChannelCredentials.Insecure }; _channel = GrpcChannel.ForAddress(grpcServerAddress, opt); }