// static void Main(string[] args) // { // Console.WriteLine("Hello World!"); // } static async Task Main(string[] args) { GrpcChannel channel = GrpcChannel.ForAddress(SERVER_ADDRESS); Greeter.GreeterClient client = new Greeter.GreeterClient(channel); HelloReply reply = await client.SayHelloAsync(new HelloRequest { Name = "GreeterClient" }); Console.WriteLine("[GrpcGreeterClient][Main] => (reply.Message): " + (reply.Message)); Console.WriteLine("Press any key to exit..."); Console.Read(); }
static async Task Main(string[] args) { using var channel = GrpcChannel.ForAddress("https://localhost:5001"); var client = new Greeter.GreeterClient(channel); var reply = await client.SayHelloAsync( new HelloRequest { Name = "GreeterClient" }); Console.WriteLine("Greeting: " + reply.Message); Console.WriteLine("Press any key to exit..."); Console.ReadKey(); }
static async Task Main(string[] args) { AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); // The port number(5001) must match the port of the gRPC server. var channel = GrpcChannel.ForAddress("http://localhost:5000"); var client = new Greeter.GreeterClient(channel); var reply = await client.SayMyNameAsync(new HelloRequest { Name = "Jose", Middlename = "P.", Lastname = "Longhi" }); Console.WriteLine("Greeting: " + reply.Message); Console.WriteLine("Press any key to exit..."); Console.ReadKey(); }
static async Task Main(string[] args) { // The port number(5001) must match the port of the gRPC server. using var channel = GrpcChannel.ForAddress("https://localhost:5001"); // Initiate a GrpcChannel containing the information for creating the connection to the gRPC service var client = new Greeter.GreeterClient(channel); // Using the GrpcChannel to construct the Greeter client var reply = await client.SayHelloAsync( new HelloRequest { Name = "GreeterClient" }); // call the asynchronous remote process, `HelloRequest`. Console.WriteLine("Greeting: " + reply.Message); Console.WriteLine("Press any key to exit..."); Console.ReadKey(); }
static async Task Main(string[] args) { // The port number(5001) must match the port of the gRPC server. var channel = GrpcChannel.ForAddress("https://localhost:5001"); var client = new Greeter.GreeterClient(channel); var reply = await client.SayHelloAsync( new HelloRequest { Name = "World" }); Console.WriteLine("Greeting: " + reply.Message); Console.WriteLine("Press any key to exit..."); Console.ReadKey(); }
static async Task Main(string[] args) { // The port number(5001) must match the port of the gRPC server. var channel = GrpcChannel.ForAddress("https://localhost:5001"); var client = new Greeter.GreeterClient(channel); Boolean isexit = true; while (isexit) { Console.WriteLine("Enter Your Name to send request to the server : "); String myName = Console.ReadLine(); var reply = await client.SayHelloAsync( new HelloRequest { Name = myName }); Console.WriteLine("Hello world : " + reply.Message); Console.WriteLine("Enter YourFriend Name : "); String friendName = Console.ReadLine(); var serverreply = await client.ServerMessageAsync( new HelloRequest { Name = friendName }); Console.WriteLine("Message from Server -> " + serverreply.Message); Console.WriteLine("Do you want to continue say Y or N"); string YN = Console.ReadLine(); if (YN.ToLower() == "y") { isexit = true; } else { isexit = false; } Console.WriteLine("========================== ============"); Console.WriteLine(""); } Console.WriteLine("Press any key to exit..."); Console.ReadKey(); //var reply = await client.SayHelloAsync( // new HelloRequest { Name = "GreeterClient" }); //Console.WriteLine("Greeting: " + reply.Message); //Console.WriteLine("Press any key to exit..."); //Console.ReadKey(); }
static async Task Main(string[] args) { using var grpc = GrpcChannel.ForAddress("https://localhost:5001"); var client = new Greeter.GreeterClient(grpc); var request = new HelloRequest { Name = "Everybody!" }; var response = await client.SayHelloAsync(request); Console.WriteLine(response.Message); Console.WriteLine("Press a key to exit..."); Console.ReadKey(); }
static async Task Main(string[] args) { AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); using var channel = GrpcChannel.ForAddress("http://localhost:5000"); // dropped SSL due to MacOS issues: https://docs.microsoft.com/ro-ro/aspnet/core/grpc/troubleshoot?view=aspnetcore-3.1#unable-to-start-aspnet-core-grpc-app-on-macos var client = new Greeter.GreeterClient(channel); var reply = await client.SayHelloAsync( new HelloRequest { Name = "GreeterClient" }); Console.WriteLine("Greeting: " + reply.Message); Console.WriteLine("Press any key to exit..."); Console.ReadKey(); }
static async Task Run() { // https://docs.microsoft.com/en-us/aspnet/core/grpc/troubleshoot?view=aspnetcore-3.1#call-insecure-grpc-services-with-net-core-client AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); using var channel = GrpcChannel.ForAddress("http://localhost:5000"); var client = new Greeter.GreeterClient(channel); var reply = await client.SayHelloAsync(new HelloRequest { Name = "GreeterClient" }); Console.WriteLine("Greeting: " + reply.Message); Console.WriteLine("Press any key to exit..."); Console.ReadKey(); }
// 为什么每次调用创建一个channel会有很大的性能损失 // 因为每次调用都需要在客户端和服务端之间进行多次网络往返,以创建一个新的HTTP/2连接,主要开销如下: // 1:打开一个socket 2:建立TCP连接 3:TLS握手 4:开始HTTP/2连接 5:开始Grpc调用 // 创建的client是轻量级的,不需要被缓存和重用 // 一个channel可以创建多个不同类型的client // channel创建的client是线程安全的 // channel创建的client可以同时多次调用 static async Task Main(string[] args) { var channel = GrpcChannel.ForAddress("https://localhost:5001"); // 下面创建一个已经授权的channl,那么经它生成的client就不要再一遍遍写授权代码了。 var authenticatedChannel = CreateAuthenticatedAChannel("https://localhost:5001"); var authenticatedClient = new Greeter.GreeterClient(authenticatedChannel); var client = new Greeter.GreeterClient(channel); // 方式1 var reply = await client.SayHelloAsync( new HelloRequest { Name = "GreeterClient" } ); //var payload = new PayloadResponse(); var status = new GrpcDemo.Status(); status.Detail = Any.Pack(new HelloRequest() { Name = "marsonshine" }); if (status.Detail.Is(HelloRequest.Descriptor)) { } // oneof try { var oneofResult = await client.OneofReturnValueAsync(new Empty(), deadline : DateTime.UtcNow.AddSeconds(5)); // 还可以设置deadline,更有利于系统的伸缩性 switch (oneofResult.ResultCase) { case ResponseMessage.ResultOneofCase.Person: break; case ResponseMessage.ResultOneofCase.Error: break; default: break; } } catch (RpcException ex) when(ex.StatusCode == StatusCode.DeadlineExceeded) { Console.WriteLine("Timeout!"); } Console.WriteLine("Greeting: " + reply.Message); Console.WriteLine("请按任意键结束..."); Console.ReadKey(); }
static async Task Main(string[] args) { // This switch must be set before creating the GrpcChannel/HttpClient. AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); // The port number(5001) must match the port of the gRPC server. using var channel = GrpcChannel.ForAddress("http://127.0.0.1:5000"); var client = new Greeter.GreeterClient(channel); var reply = await client.SayHelloAsync( new HelloRequest { Name = "GreeterClient" }); Console.WriteLine("Greeting: " + reply.Message); Console.WriteLine("Press any key to exit..."); Console.ReadKey(); }
static async Task Main(string[] args) { // This switch must be set before creating the GrpcChannel/HttpClient. AppContext.SetSwitch( "System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); using var channel = GrpcChannel.ForAddress("http://localhost:5000"); var client = new Greeter.GreeterClient(channel); var reply = await client.SayHelloAsync( new HelloRequest { Name = "Ola Mundo!" }); Console.WriteLine(reply.Message); Console.WriteLine("Tem um canal bidirecional estabelecido aqui. Mas aperte qualquer tecla para sair."); Console.ReadKey(); }
static async Task Main(string[] args) { var channel = GrpcChannel.ForAddress("https://localhost:5001", new GrpcChannelOptions { MaxReceiveMessageSize = 5 * 1024 * 1024, // 5 MB MaxSendMessageSize = 2 * 1024 * 1024 // 2 MB }); var client = new Greeter.GreeterClient(channel); var reply = await client.SayHelloAsync( new HelloRequest { Name = "GreeterClient" }); Console.WriteLine("Greeting: " + reply.Message); }
public static void Greeter() { //通道,成本高昂,建议重用(工厂集成:https://docs.microsoft.com/zh-cn/aspnet/core/grpc/clientfactory?view=aspnetcore-3.1) using var channel = GrpcChannel.ForAddress("https://localhost:5001"); //客户端,成本低,无需重用 var client = new Greeter.GreeterClient(channel); var reply = client.SayHello(new HelloRequest() { Name = "GreeterClient" }); Console.WriteLine("Greeting: " + reply.Message); }
static async Task Main(string[] args) { // The port number(50051) must match the port of the gRPC server. var channel = new Channel("localhost:50051", ChannelCredentials.Insecure); var client = new Greeter.GreeterClient(channel); var reply = await client.SayHelloAsync( new HelloRequest { Name = "GreeterClient" }); Console.WriteLine("Greeting: " + reply.Message); await channel.ShutdownAsync(); Console.WriteLine("Press any key to exit..."); Console.ReadKey(); }
static async Task Main(string[] args) { var channel = new Channel("localhost:5001", ChannelCredentials.Insecure, new[] { new ChannelOption(ChannelOptions.MaxSendMessageLength, 2 * 1024 * 1024), new ChannelOption(ChannelOptions.MaxReceiveMessageLength, 5 * 1024 * 1024) }); var client = new Greeter.GreeterClient(channel); var reply = await client.SayHelloAsync( new HelloRequest { Name = "GreeterClient" }); Console.WriteLine("Greeting: " + reply.Message); await channel.ShutdownAsync(); Console.WriteLine("Press any key to exit..."); Console.ReadKey(); }
static async Task Main(string[] args) { var httpClientHandler = new HttpClientHandler(); httpClientHandler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator; var httpClient = new HttpClient(httpClientHandler); var channel = GrpcChannel.ForAddress("https://localhost:5001", new GrpcChannelOptions { HttpClient = httpClient }); var client = new Greeter.GreeterClient(channel); var reply = await client.SayHelloAsync( new HelloRequest { Name = "GreeterClient" }); Console.WriteLine("Greeting: " + reply.Message); Console.WriteLine("Press any key to exit..."); Console.ReadKey(); }
static async Task Main(string[] args) { var channel = GrpcChannel.ForAddress(Address, new GrpcChannelOptions() { }); var options = new CallOptions() .WithDeadline(DateTime.UtcNow.AddMinutes(1)) .WithWaitForReady(true); var client = new Greeter.GreeterClient(channel); var reply = await client.SayHelloAsync( new HelloRequest { Name = "GreeterClient" }, options); try { var reply2 = await client.SayHelloAgainAsync( new HelloRequest { Name = "GreeterClient" }, options); Console.WriteLine("Greeting: " + reply2.Message); Console.WriteLine("Press any key to exit..."); } catch (RpcException e) { Console.WriteLine(e); // ouch! // lets print the gRPC error message // which is "Length of `Name` cannot be more than 10 characters" Console.WriteLine(e.Status.Detail); // lets access the error code, which is `INVALID_ARGUMENT` Console.WriteLine(e.Status.StatusCode); // Want its int version for some reason? // you shouldn't actually do this, but if you need for debugging, // you can access `e.Status.StatusCode` which will give you `3` Console.WriteLine((int)e.Status.StatusCode); // Want to take specific action based on specific error? if (e.Status.StatusCode == Grpc.Core.StatusCode.InvalidArgument) { // do your thing } } await AddressBookkOperations(channel); Console.ReadKey(); }
static async Task Main(string[] args) { // This is required AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); string host; try { host = new Uri(args[0]).ToString(); } catch (Exception) { host = "https://localhost:5001"; } Console.WriteLine($"Connecting to gRPC provider on {host}"); using (var channel = GrpcChannel.ForAddress(host)) { var client = new Greeter.GreeterClient(channel); var request = new HelloRequest { Name = "Test" }; var reply = await client.SayHelloAsync(request); Console.WriteLine(reply); while (true) { sw.Reset(); Console.WriteLine(String.Empty.PadLeft(72, '=')); Console.Write("Enter your name: "); var name = Console.ReadLine(); if (bailouts.Contains(name)) { return; } sw.Start(); request = new HelloRequest { Name = name }; reply = await client.SayHelloAsync(request); sw.Stop(); Console.WriteLine(reply); Console.WriteLine($"gRPC call took {sw.ElapsedMilliseconds} ms"); } } }
static async Task Main(string[] args) { // The port number(5001) must match the port of the gRPC server. AppContext.SetSwitch( "System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); var channel = GrpcChannel.ForAddress("http://localhost:5001"); var client = new Greeter.GreeterClient(channel); for (var i = 0; i < 10000; i++) { var reply = await client.SayHelloAsync( new HelloRequest { Name = "GreeterClient" }); // Console.WriteLine("Greeting: " + reply.Message); } // Console.WriteLine("Press any key to exit..."); // Console.ReadKey(); }
static async Task Main(string[] args) { Console.WriteLine("Start gRPC client..."); // Call insecure gRPC services with .NET Core client, visit https://docs.microsoft.com/en-us/aspnet/core/grpc/troubleshoot?view=aspnetcore-3.1#call-insecure-grpc-services-with-net-core-client // This switch must be set before creating the GrpcChannel/HttpClient. AppContext.SetSwitch( "System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); // The port number(5001) must match the port of the gRPC server. using var channel = GrpcChannel.ForAddress("http://localhost:5000"); var client = new Greeter.GreeterClient(channel); var reply = await client.SayHelloAsync( new HelloRequest { Name = "GreeterClient" }); Console.WriteLine("Greeting: " + reply.Message); Console.WriteLine("Press any key to exit..."); Console.ReadKey(); }
static async Task Main(string[] args) { // The port number(5001) must match the port of the gRPC server. using var channel = GrpcChannel.ForAddress("https://localhost:5001"); var client = new Greeter.GreeterClient(channel); var watch = new Stopwatch(); watch.Start(); var reply = await client.SayHelloAsync( new HelloRequest { Name = "GreeterClient" }); watch.Stop(); var responseTime = watch.ElapsedMilliseconds; Console.WriteLine("Greeting: " + reply.Message); Console.WriteLine("The reply lasted: " + responseTime + " ms"); Console.WriteLine("Press any key to exit..."); Console.ReadKey(); }
/// <summary> /// Main method /// </summary> /// <param name="args"></param> /// <returns></returns> static async Task Main(string[] args) { // The port number(5001) must match the port of the gRPC server. using var channel = GrpcChannel.ForAddress("https://localhost:5001"); var client = new Greeter.GreeterClient(channel); try { var reply = await client.SayHelloAsync( new HelloRequest { Name = "GrpcClient" }); Console.WriteLine("Connected: " + reply.Message); Console.ReadKey(); } catch (Exception error) { Console.WriteLine("Not connected: " + error.Message); Console.ReadKey(); } }
static async Task Main(string[] args) { // The port number(5001) must match the port of the gRPC server. using var channel = GrpcChannel.ForAddress("https://localhost:5001"); var client = new Greeter.GreeterClient(channel); var postClient = new RemotePost.RemotePostClient(channel); //var reply = await client.SayHelloAsync( //new HelloRequest { Name = "GreeterClient" }); var reply2 = await postClient.AddPostAsync( new PostModel { Id = 1, Description = "Nimic", Domain = "Altul", Date = Timestamp.FromDateTime(DateTime.UtcNow) }); Console.WriteLine("Result: " + reply2.Message); Console.WriteLine("Press any key to exit..."); Console.ReadKey(); }
static async Task Main(string[] args) { var headers = new Metadata(); headers.Add("Authorization", $"Bearer {_token}"); // The port number(5001) must match the port of the gRPC server. using var channel = GrpcChannel.ForAddress("https://localhost:5001"); var client = new Greeter.GreeterClient(channel); var reply = await client.SayHelloAsync( new HelloRequest { Name = "GreeterClient" }, headers); Console.WriteLine("Greeting: " + reply.Message); var authenticatedChannel = CreateAuthenticatedChannel("https://localhost:5001"); var authenticatedClient = new Greeter.GreeterClient(authenticatedChannel); var response = await authenticatedClient.SayHelloAsync(new HelloRequest { Name = "Greeter by Authenticated Client" }); Console.WriteLine("Greeting: " + response.Message); Console.WriteLine("Press any key to exit..."); Console.ReadKey(); }
static void Main(string[] args) { var channel = GrpcChannel.ForAddress("https://localhost:5001"); var client = new Greeter.GreeterClient(channel); var reply = client.SayHello(new HelloRequest { Name = "GreeterClient" }); Console.WriteLine("Greeting:" + reply.Message); string id; while ((id = Console.ReadLine()) != "3") { var empClient = new Employee.EmployeeClient(channel); var emp = empClient.GetEmpInfo(new EmpRequest { Id = Convert.ToInt32(id) }); Console.WriteLine(emp); } Console.ReadKey(); }
static void TestConcurrent() { Console.WriteLine($"{DateTime.Now} - Starting {nameof(TestConcurrent)} {TotalRequests} requests"); var stopwatch = Stopwatch.StartNew(); Parallel.For(0, TotalRequests, parallelOptions, (i) => { if (LogDetails) { Console.WriteLine($"{DateTime.Now} - Start request {i}"); } using var channel = GrpcChannel.ForAddress("https://localhost:5001"); var client = new Greeter.GreeterClient(channel); var reply = client.GetTime(new Empty()); if (LogDetails) { Console.WriteLine($"{DateTime.Now} - End request {i}: {reply}"); } }); stopwatch.Stop(); Console.WriteLine($"{DateTime.Now} - {nameof(TestConcurrent)} for {TotalRequests} requests took: {stopwatch.ElapsedMilliseconds}ms"); }
static void TestSequential() { Console.WriteLine($"{DateTime.Now} - Starting {nameof(TestSequential)} {TotalRequests} requests"); var stopwatch = Stopwatch.StartNew(); for (int i = 0; i < TotalRequests; i++) { if (LogDetails) { Console.WriteLine($"{DateTime.Now} - Start request {i}"); } using var channel = GrpcChannel.ForAddress("https://localhost:5001"); var client = new Greeter.GreeterClient(channel); var reply = client.GetTime(new Empty()); if (LogDetails) { Console.WriteLine($"{DateTime.Now} - End request {i}: {reply}"); } } stopwatch.Stop(); Console.WriteLine($"{DateTime.Now} - {nameof(TestSequential)} for {TotalRequests} requests took: {stopwatch.ElapsedMilliseconds}ms"); }
static async Task Main(string[] args) { using var channel = CreateAuthenticatedChannel("https://localhost:5001"); //using var channel = GrpcChannel.ForAddress("https://localhost:5001", new GrpcChannelOptions //{ // MaxSendMessageSize = 10 * 1024 * 1024, // ThrowOperationCanceledOnCancellation = true //}); _token = await Authenticate(); var client = new Greeter.GreeterClient(channel); try { var reply = await client.SayHelloAsync(new HelloRequest { Name = "GrpcGreeterClient" }); Console.WriteLine("Greeting: " + reply.Message); } catch (RpcException ex) when(ex.StatusCode == StatusCode.DeadlineExceeded) { Console.WriteLine("Greeting timeout."); } // stream from service try { var tokenSource = new CancellationTokenSource(); var call = client.StreamingFromService(new ExampleRequest { PageIndex = 1, PageSize = 10, IsDescending = false }, cancellationToken: tokenSource.Token); while (await call.ResponseStream.MoveNext()) { Console.WriteLine($"response age {call.ResponseStream.Current.Age}"); if (call.ResponseStream.Current.Age > 80) { tokenSource.Cancel(); } } } catch (OperationCanceledException ex) { Console.WriteLine($"request cancel by client {ex.Message}"); } // stream from client var clientCall = client.StreamingFromClient(); for (var i = 0; i < 5; i++) { await clientCall.RequestStream.WriteAsync(new ExampleRequest { PageIndex = i, PageSize = i, IsDescending = false }); } // await clientCall.RequestStream.CompleteAsync(); //var clientResponse = clientCall.GetTrailers(); //Console.WriteLine($"client end meta data {clientResponse.GetValue("my-trailer-name")}"); // both stream var bothstream = client.StreamingBothWays(); Console.WriteLine($"Starting background task to receive messages"); var readTask = Task.Run(async() => { await foreach (var response in bothstream.ResponseStream.ReadAllAsync()) { Console.WriteLine($"response age {response.Age}"); } }); Console.WriteLine("Starting to send messages"); Console.WriteLine("Type a message to echo then press enter."); while (true) { var result = Console.ReadLine(); if (string.IsNullOrEmpty(result)) { break; } await bothstream.RequestStream.WriteAsync(new ExampleRequest { PageIndex = 100, PageSize = 200, IsDescending = true }); } Console.WriteLine("Disconnecting"); await bothstream.RequestStream.CompleteAsync(); Console.WriteLine("Press any key to exit..."); Console.ReadKey(); }