gRPC Basics - C#

This tutorial provides a basic C# programmer’s introduction to working with gRPC.

By walking through this example you’ll learn how to:

  • Define a service in a .proto file.
  • Generate server and client code using the protocol buffer compiler.
  • Use the C# gRPC API to write a simple client and server for your service.

It assumes that you have read theOverview and are familiarwithprotocol buffers. Note that theexample in this tutorial uses the proto3 version of the protocol bufferslanguage: you can find out more in theproto3 language guide andC# generated code reference.

Why use gRPC?

Our example is a simple route mapping application that lets clients getinformation about features on their route, create a summary of their route, andexchange route information such as traffic updates with the server and otherclients.

With gRPC we can define our service once in a .proto file and implement clientsand servers in any of gRPC’s supported languages, which in turn can be run inenvironments ranging from servers inside Google to your own tablet - all thecomplexity of communication between different languages and environments ishandled for you by gRPC. We also get all the advantages of working with protocolbuffers, including efficient serialization, a simple IDL, and easy interfaceupdating.

Example code and setup

The example code for our tutorial is ingrpc/grpc/examples/csharp/RouteGuide. Todownload the example, clone the grpc repository by running the followingcommand:

  1. $ git clone -b v1.28.1 https://github.com/grpc/grpc
  2. $ cd grpc

All the files for this tutorial are in the directoryexamples/csharp/RouteGuide. Open the solutionexamples/csharp/RouteGuide/RouteGuide.sln from Visual Studio (Windows or Mac) or Visual Studio Code.For additional installation details, see theHow to useinstructions.

Defining the service

Our first step (as you’ll know from theOverview) is todefine the gRPC service and the method request and response types usingprotocol buffers.You can see the complete .proto file inexamples/protos/route_guide.proto.

To define a service, you specify a named service in your .proto file:

  1. service RouteGuide {
  2. ...
  3. }

Then you define rpc methods inside your service definition, specifying theirrequest and response types. gRPC lets you define four kinds of service method,all of which are used in the RouteGuide service:

  • A simple RPC where the client sends a request to the server using the clientobject and waits for a response to come back, just like a normal functioncall.
  1. // Obtains the feature at a given position.
  2. rpc GetFeature(Point) returns (Feature) {}
  • A server-side streaming RPC where the client sends a request to the serverand gets a stream to read a sequence of messages back. The client reads fromthe returned stream until there are no more messages. As you can see in ourexample, you specify a server-side streaming method by placing the streamkeyword before the response type.
  1. // Obtains the Features available within the given Rectangle. Results are
  2. // streamed rather than returned at once (e.g. in a response message with a
  3. // repeated field), as the rectangle may cover a large area and contain a
  4. // huge number of features.
  5. rpc ListFeatures(Rectangle) returns (stream Feature) {}
  • A client-side streaming RPC where the client writes a sequence of messagesand sends them to the server, again using a provided stream. Once the clienthas finished writing the messages, it waits for the server to read them alland return its response. You specify a client-side streaming method by placingthe stream keyword before the request type.
  1. // Accepts a stream of Points on a route being traversed, returning a
  2. // RouteSummary when traversal is completed.
  3. rpc RecordRoute(stream Point) returns (RouteSummary) {}
  • A bidirectional streaming RPC where both sides send a sequence of messagesusing a read-write stream. The two streams operate independently, so clientsand servers can read and write in whatever order they like: for example, theserver could wait to receive all the client messages before writing itsresponses, or it could alternately read a message then write a message, orsome other combination of reads and writes. The order of messages in eachstream is preserved. You specify this type of method by placing the streamkeyword before both the request and the response.
  1. // Accepts a stream of RouteNotes sent while a route is being traversed,
  2. // while receiving other RouteNotes (e.g. from other users).
  3. rpc RouteChat(stream RouteNote) returns (stream RouteNote) {}

Our .proto file also contains protocol buffer message type definitions for allthe request and response types used in our service methods - for example, here’sthe Point message type:

  1. // Points are represented as latitude-longitude pairs in the E7 representation
  2. // (degrees multiplied by 10**7 and rounded to the nearest integer).
  3. // Latitudes should be in the range +/- 90 degrees and longitude should be in
  4. // the range +/- 180 degrees (inclusive).
  5. message Point {
  6. int32 latitude = 1;
  7. int32 longitude = 2;
  8. }

Generating client and server code

Next we need to generate the gRPC client and server interfaces from our .protoservice definition. This can be done by invoking the protocol buffer compiler protoc witha special gRPC C# plugin from the command line, but starting from version1.17 the Grpc.Tools NuGet package integrates with MSBuild to provideautomatic C# code generationfrom .proto files, which gives much better developer experience by runningthe right commands for you as part of the build.

This example already has a dependency on Grpc.Tools NuGet package and theroute_guide.proto has already been added to the project, so the only thingneeded to generate the client and server code is to build the solution.That can be done by running dotnet build RouteGuide.sln or building directlyin Visual Studio.

The build regenerates the following filesunder the RouteGuide/obj/Debug/TARGET_FRAMEWORK directory:

  • RouteGuide.cs contains all the protocol buffer code to populate,serialize, and retrieve our request and response message types
  • RouteGuideGrpc.cs provides generated client and server classes,including:
    • an abstract class RouteGuide.RouteGuideBase to inherit from when definingRouteGuide service implementations
    • a class RouteGuide.RouteGuideClient that can be used to access remoteRouteGuide instances

Creating the server

First let’s look at how we create a RouteGuide server. If you’re onlyinterested in creating gRPC clients, you can skip this section and go straighttoCreating the client (though you might find it interestinganyway!).

There are two parts to making our RouteGuide service do its job:

  • Implementing the service functionality by inheriting from the base classgenerated from our service definition: doing the actual “work” of our service.
  • Running a gRPC server to listen for requests from clients and return theservice responses.

You can find our example RouteGuide server inexamples/csharp/RouteGuide/RouteGuideServer/RouteGuideImpl.cs.Let’s take a closer look at how it works.

Implementing RouteGuide

As you can see, our server has a RouteGuideImpl class that inherits from thegenerated RouteGuide.RouteGuideBase:

  1. // RouteGuideImpl provides an implementation of the RouteGuide service.
  2. public class RouteGuideImpl : RouteGuide.RouteGuideBase

Simple RPC

RouteGuideImpl implements all our service methods. Let’s look at the simplesttype first, GetFeature, which just gets a Point from the client and returnsthe corresponding feature information from its database in a Feature.

  1. public override Task<Feature> GetFeature(Point request, Grpc.Core.ServerCallContext context)
  2. {
  3. return Task.FromResult(CheckFeature(request));
  4. }

The method is passed a context for the RPC (which is empty in the alpharelease), the client’s Point protocol buffer request, and returns a Featureprotocol buffer. In the method we create the Feature with the appropriateinformation, and then return it. To allow asynchronous implementation, themethod returns Task<Feature> rather than just Feature. You are free toperform your computations synchronously and return the result once you’vefinished, just as we do in the example.

Server-side streaming RPC

Now let’s look at something a bit more complicated - a streaming RPC.ListFeatures is a server-side streaming RPC, so we need to send back multipleFeature protocol buffers to our client.

  1. // in RouteGuideImpl
  2. public override async Task ListFeatures(Rectangle request,
  3. Grpc.Core.IServerStreamWriter<Feature> responseStream,
  4. Grpc.Core.ServerCallContext context)
  5. {
  6. var responses = features.FindAll( (feature) => feature.Exists() && request.Contains(feature.Location) );
  7. foreach (var response in responses)
  8. {
  9. await responseStream.WriteAsync(response);
  10. }
  11. }

As you can see, here the request object is a Rectangle in which our clientwants to find Features, but instead of returning a simple response we need towrite responses to an asynchronous stream IServerStreamWriter using asyncmethod WriteAsync.

Client-side streaming RPC

Similarly, the client-side streaming method RecordRoute uses anIAsyncEnumerator,to read the stream of requests using the async method MoveNext and theCurrent property.

  1. public override async Task<RouteSummary> RecordRoute(Grpc.Core.IAsyncStreamReader<Point> requestStream,
  2. Grpc.Core.ServerCallContext context)
  3. {
  4. int pointCount = 0;
  5. int featureCount = 0;
  6. int distance = 0;
  7. Point previous = null;
  8. var stopwatch = new Stopwatch();
  9. stopwatch.Start();
  10. while (await requestStream.MoveNext())
  11. {
  12. var point = requestStream.Current;
  13. pointCount++;
  14. if (CheckFeature(point).Exists())
  15. {
  16. featureCount++;
  17. }
  18. if (previous != null)
  19. {
  20. distance += (int) previous.GetDistance(point);
  21. }
  22. previous = point;
  23. }
  24. stopwatch.Stop();
  25. return new RouteSummary
  26. {
  27. PointCount = pointCount,
  28. FeatureCount = featureCount,
  29. Distance = distance,
  30. ElapsedTime = (int)(stopwatch.ElapsedMilliseconds / 1000)
  31. };
  32. }

Bidirectional streaming RPC

Finally, let’s look at our bidirectional streaming RPC RouteChat.

  1. public override async Task RouteChat(Grpc.Core.IAsyncStreamReader<RouteNote> requestStream,
  2. Grpc.Core.IServerStreamWriter<RouteNote> responseStream,
  3. Grpc.Core.ServerCallContext context)
  4. {
  5. while (await requestStream.MoveNext())
  6. {
  7. var note = requestStream.Current;
  8. List<RouteNote> prevNotes = AddNoteForLocation(note.Location, note);
  9. foreach (var prevNote in prevNotes)
  10. {
  11. await responseStream.WriteAsync(prevNote);
  12. }
  13. }
  14. }

Here the method receives both requestStream and responseStream arguments.Reading the requests is done the same way as in the client-side streaming methodRecordRoute. Writing the responses is done the same way as in the server-sidestreaming method ListFeatures.

Starting the server

Once we’ve implemented all our methods, we also need to start up a gRPC serverso that clients can actually use our service. The following snippet shows how wedo this for our RouteGuide service:

  1. var features = RouteGuideUtil.ParseFeatures(RouteGuideUtil.DefaultFeaturesFile);
  2. Server server = new Server
  3. {
  4. Services = { RouteGuide.BindService(new RouteGuideImpl(features)) },
  5. Ports = { new ServerPort("localhost", Port, ServerCredentials.Insecure) }
  6. };
  7. server.Start();
  8. Console.WriteLine("RouteGuide server listening on port " + port);
  9. Console.WriteLine("Press any key to stop the server...");
  10. Console.ReadKey();
  11. server.ShutdownAsync().Wait();

As you can see, we build and start our server using Grpc.Core.Server class. Todo this, we:

  • Create an instance of Grpc.Core.Server.
  • Create an instance of our service implementation class RouteGuideImpl.
  • Register our service implementation by adding its service definition to theServices collection (We obtain the service definition from the generatedRouteGuide.BindService method).
  • Specify the address and port we want to use to listen for client requests.This is done by adding ServerPort to the Ports collection.
  • Call Start on the server instance to start an RPC server for our service.

Creating the client

In this section, we’ll look at creating a C# client for our RouteGuideservice. You can see our complete example client code inexamples/csharp/RouteGuide/RouteGuideClient/Program.cs.

Creating a client object

To call service methods, we first need to create a client object (also referredto as stub for other gRPC languages).

First, we need to create a gRPC client channel that will connect to gRPC server.Then, we create an instance of the RouteGuite.RouteGuideClient class generatedfrom our .proto, passing the channel as an argument.

  1. Channel channel = new Channel("127.0.0.1:50052", ChannelCredentials.Insecure);
  2. var client = new RouteGuide.RouteGuideClient(channel);
  3. // YOUR CODE GOES HERE
  4. channel.ShutdownAsync().Wait();

Calling service methods

Now let’s look at how we call our service methods. gRPC C# provides asynchronousversions of each of the supported method types. For convenience, gRPC C# alsoprovides a synchronous method stub, but only for simple (single request/singleresponse) RPCs.

Simple RPC

Calling the simple RPC GetFeature in a synchronous way is nearly asstraightforward as calling a local method.

  1. Point request = new Point { Latitude = 409146138, Longitude = -746188906 };
  2. Feature feature = client.GetFeature(request);

As you can see, we create and populate a request protocol buffer object (in ourcase Point), and call the desired method on the client object, passing it therequest. If the RPC finishes with success, the response protocol buffer (in ourcase Feature) is returned. Otherwise, an exception of type RpcException isthrown, indicating the status code of the problem.

Alternatively, if you are in an async context, you can call an asynchronousversion of the method and use the await keyword to await the result:

  1. Point request = new Point { Latitude = 409146138, Longitude = -746188906 };
  2. Feature feature = await client.GetFeatureAsync(request);

Streaming RPCs

Now let’s look at our streaming methods. If you’ve already readCreating theserver some of this may look very familiar - streaming RPCs areimplemented in a similar way on both sides. The difference with respect tosimple call is that the client methods return an instance of a call object. Thisprovides access to request/response streams and/or the asynchronous result,depending on the streaming type you are using.

Here’s where we call the server-side streaming method ListFeatures, which hasthe property ReponseStream of type IAsyncEnumerator<Feature>

  1. using (var call = client.ListFeatures(request))
  2. {
  3. while (await call.ResponseStream.MoveNext())
  4. {
  5. Feature feature = call.ResponseStream.Current;
  6. Console.WriteLine("Received " + feature.ToString());
  7. }
  8. }

The client-side streaming method RecordRoute is similar, except we use theproperty RequestStream to write the requests one by one using WriteAsync,and eventually signal that no more requests will be sent using CompleteAsync.The method result can be obtained through the property ResponseAsync.

  1. using (var call = client.RecordRoute())
  2. {
  3. foreach (var point in points)
  4. {
  5. await call.RequestStream.WriteAsync(point);
  6. }
  7. await call.RequestStream.CompleteAsync();
  8. RouteSummary summary = await call.ResponseAsync;
  9. }

Finally, let’s look at our bidirectional streaming RPC RouteChat. In thiscase, we write the request to RequestStream and receive the responses fromResponseStream. As you can see from the example, the streams are independentof each other.

  1. using (var call = client.RouteChat())
  2. {
  3. var responseReaderTask = Task.Run(async () =>
  4. {
  5. while (await call.ResponseStream.MoveNext())
  6. {
  7. var note = call.ResponseStream.Current;
  8. Console.WriteLine("Received " + note);
  9. }
  10. });
  11. foreach (RouteNote request in requests)
  12. {
  13. await call.RequestStream.WriteAsync(request);
  14. }
  15. await call.RequestStream.CompleteAsync();
  16. await responseReaderTask;
  17. }

Try it out!

Build the client and server:

  • Using Visual Studio (or Visual Studio For Mac)
  • Open the solution examples/csharp/RouteGuide/RouteGuide.sln and select Build.
  • Using dotnet command line tool
  • Run dotnet build RouteGuide.sln from the examples/csharp/RouteGuidedirectory. For additional instructions on building the gRPC example with thedotnet command line tool, seeQuick Start.

Run the server:

  1. > cd RouteGuideServer/bin/Debug/netcoreapp2.1
  2. > dotnet exec RouteGuideServer.dll

From a different terminal, run the client:

  1. > cd RouteGuideClient/bin/Debug/netcoreapp2.1
  2. > dotnet exec RouteGuideClient.dll

You can also run the server and client directly from Visual Studio.