|
| 1 | +# Grpc.Net.Client |
| 2 | + |
| 3 | +`Grpc.Net.Client` is a gRPC client library for .NET. |
| 4 | + |
| 5 | +## Configure gRPC client |
| 6 | + |
| 7 | +gRPC clients are concrete client types that are [generated from `.proto` files](https://docs.microsoft.com/aspnet/core/grpc/basics#generated-c-assets). The concrete gRPC client has methods that translate to the gRPC service in the `.proto` file. For example, a service called `Greeter` generates a `GreeterClient` type with methods to call the service. |
| 8 | + |
| 9 | +A gRPC client is created from a channel. Start by using `GrpcChannel.ForAddress` to create a channel, and then use the channel to create a gRPC client: |
| 10 | + |
| 11 | +```csharp |
| 12 | +var channel = GrpcChannel.ForAddress("https://localhost:5001"); |
| 13 | +var client = new Greet.GreeterClient(channel); |
| 14 | +``` |
| 15 | + |
| 16 | +A channel represents a long-lived connection to a gRPC service. When a channel is created, it's configured with options related to calling a service. For example, the `HttpClient` used to make calls, the maximum send and receive message size, and logging can be specified on `GrpcChannelOptions` and used with `GrpcChannel.ForAddress`. For a complete list of options, see [client configuration options](https://docs.microsoft.com/aspnet/core/grpc/configuration#configure-client-options). |
| 17 | + |
| 18 | +```csharp |
| 19 | +var channel = GrpcChannel.ForAddress("https://localhost:5001"); |
| 20 | + |
| 21 | +var greeterClient = new Greet.GreeterClient(channel); |
| 22 | +var counterClient = new Count.CounterClient(channel); |
| 23 | + |
| 24 | +// Use clients to call gRPC services |
| 25 | +``` |
| 26 | + |
| 27 | +## Make gRPC calls |
| 28 | + |
| 29 | +A gRPC call is initiated by calling a method on the client. The gRPC client will handle message serialization and addressing the gRPC call to the correct service. |
| 30 | + |
| 31 | +gRPC has different types of methods. How the client is used to make a gRPC call depends on the type of method called. The gRPC method types are: |
| 32 | + |
| 33 | +* Unary |
| 34 | +* Server streaming |
| 35 | +* Client streaming |
| 36 | +* Bi-directional streaming |
| 37 | + |
| 38 | +### Unary call |
| 39 | + |
| 40 | +A unary call starts with the client sending a request message. A response message is returned when the service finishes. |
| 41 | + |
| 42 | +```csharp |
| 43 | +var client = new Greet.GreeterClient(channel); |
| 44 | +var response = await client.SayHelloAsync(new HelloRequest { Name = "World" }); |
| 45 | + |
| 46 | +Console.WriteLine("Greeting: " + response.Message); |
| 47 | +// Greeting: Hello World |
| 48 | +``` |
| 49 | + |
| 50 | +Each unary service method in the `.proto` file will result in two .NET methods on the concrete gRPC client type for calling the method: an asynchronous method and a blocking method. For example, on `GreeterClient` there are two ways of calling `SayHello`: |
| 51 | + |
| 52 | +* `GreeterClient.SayHelloAsync` - calls `Greeter.SayHello` service asynchronously. Can be awaited. |
| 53 | +* `GreeterClient.SayHello` - calls `Greeter.SayHello` service and blocks until complete. Don't use in asynchronous code. |
| 54 | + |
| 55 | +### Server streaming call |
| 56 | + |
| 57 | +A server streaming call starts with the client sending a request message. `ResponseStream.MoveNext()` reads messages streamed from the service. The server streaming call is complete when `ResponseStream.MoveNext()` returns `false`. |
| 58 | + |
| 59 | +```csharp |
| 60 | +var client = new Greet.GreeterClient(channel); |
| 61 | +using var call = client.SayHellos(new HelloRequest { Name = "World" }); |
| 62 | + |
| 63 | +while (await call.ResponseStream.MoveNext()) |
| 64 | +{ |
| 65 | + Console.WriteLine("Greeting: " + call.ResponseStream.Current.Message); |
| 66 | + // "Greeting: Hello World" is written multiple times |
| 67 | +} |
| 68 | +``` |
| 69 | + |
| 70 | +When using C# 8 or later, the `await foreach` syntax can be used to read messages. The `IAsyncStreamReader<T>.ReadAllAsync()` extension method reads all messages from the response stream: |
| 71 | + |
| 72 | +```csharp |
| 73 | +var client = new Greet.GreeterClient(channel); |
| 74 | +using var call = client.SayHellos(new HelloRequest { Name = "World" }); |
| 75 | + |
| 76 | +await foreach (var response in call.ResponseStream.ReadAllAsync()) |
| 77 | +{ |
| 78 | + Console.WriteLine("Greeting: " + response.Message); |
| 79 | + // "Greeting: Hello World" is written multiple times |
| 80 | +} |
| 81 | +``` |
| 82 | + |
| 83 | +### Client streaming call |
| 84 | + |
| 85 | +A client streaming call starts *without* the client sending a message. The client can choose to send messages with `RequestStream.WriteAsync`. When the client has finished sending messages, `RequestStream.CompleteAsync()` should be called to notify the service. The call is finished when the service returns a response message. |
| 86 | + |
| 87 | +```csharp |
| 88 | +var client = new Counter.CounterClient(channel); |
| 89 | +using var call = client.AccumulateCount(); |
| 90 | + |
| 91 | +for (var i = 0; i < 3; i++) |
| 92 | +{ |
| 93 | + await call.RequestStream.WriteAsync(new CounterRequest { Count = 1 }); |
| 94 | +} |
| 95 | +await call.RequestStream.CompleteAsync(); |
| 96 | + |
| 97 | +var response = await call; |
| 98 | +Console.WriteLine($"Count: {response.Count}"); |
| 99 | +// Count: 3 |
| 100 | +``` |
| 101 | + |
| 102 | +### Bi-directional streaming call |
| 103 | + |
| 104 | +A bi-directional streaming call starts *without* the client sending a message. The client can choose to send messages with `RequestStream.WriteAsync`. Messages streamed from the service are accessible with `ResponseStream.MoveNext()` or `ResponseStream.ReadAllAsync()`. The bi-directional streaming call is complete when the `ResponseStream` has no more messages. |
| 105 | + |
| 106 | +```csharp |
| 107 | +var client = new Echo.EchoClient(channel); |
| 108 | +using var call = client.Echo(); |
| 109 | + |
| 110 | +Console.WriteLine("Starting background task to receive messages"); |
| 111 | +var readTask = Task.Run(async () => |
| 112 | +{ |
| 113 | + await foreach (var response in call.ResponseStream.ReadAllAsync()) |
| 114 | + { |
| 115 | + Console.WriteLine(response.Message); |
| 116 | + // Echo messages sent to the service |
| 117 | + } |
| 118 | +}); |
| 119 | + |
| 120 | +Console.WriteLine("Starting to send messages"); |
| 121 | +Console.WriteLine("Type a message to echo then press enter."); |
| 122 | +while (true) |
| 123 | +{ |
| 124 | + var result = Console.ReadLine(); |
| 125 | + if (string.IsNullOrEmpty(result)) |
| 126 | + { |
| 127 | + break; |
| 128 | + } |
| 129 | + |
| 130 | + await call.RequestStream.WriteAsync(new EchoMessage { Message = result }); |
| 131 | +} |
| 132 | + |
| 133 | +Console.WriteLine("Disconnecting"); |
| 134 | +await call.RequestStream.CompleteAsync(); |
| 135 | +await readTask; |
| 136 | +``` |
| 137 | + |
| 138 | +For best performance, and to avoid unnecessary errors in the client and service, try to complete bi-directional streaming calls gracefully. A bi-directional call completes gracefully when the server has finished reading the request stream and the client has finished reading the response stream. The preceding sample call is one example of a bi-directional call that ends gracefully. In the call, the client: |
| 139 | + |
| 140 | +1. Starts a new bi-directional streaming call by calling `EchoClient.Echo`. |
| 141 | +2. Creates a background task to read messages from the service using `ResponseStream.ReadAllAsync()`. |
| 142 | +3. Sends messages to the server with `RequestStream.WriteAsync`. |
| 143 | +4. Notifies the server it has finished sending messages with `RequestStream.CompleteAsync()`. |
| 144 | +5. Waits until the background task has read all incoming messages. |
| 145 | + |
| 146 | +During a bi-directional streaming call, the client and service can send messages to each other at any time. The best client logic for interacting with a bi-directional call varies depending upon the service logic. |
| 147 | + |
| 148 | +## Links |
| 149 | + |
| 150 | +* [Documentation](https://docs.microsoft.com/aspnet/core/grpc/client) |
| 151 | +* [grpc-dotnet GitHub](https://github.com/grpc/grpc-dotnet) |
0 commit comments