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 familiarwithprotocolbuffers. Notethat the example in this tutorial uses the proto3 version of the protocolbuffers language: you can find out more intheproto3 languageguide andC++generated codeguide.

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/cpp/route_guide. Todownload the example, clone the grpc repository by running the followingcommand:

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

Then change your current directory to examples/cpp/route_guide:

  1. $ cd examples/cpp/route_guide

You also should have the relevant tools installed to generate the server andclient interface code - if you don’t already, follow the setup instructions inthe C++ quick start guide.

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 stuband waits for a response to come back, just like a normal function call.
  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. We do this using the protocol buffer compiler protoc witha special gRPC C++ plugin.

For simplicity, we’ve provided aMakefilethat runs protoc for you with the appropriate plugin, input, and output (ifyou want to run this yourself, make sure you’ve installed protoc and followedthe gRPC codeinstallation instructions first):

  1. $ make route_guide.grpc.pb.cc route_guide.pb.cc

which actually runs:

  1. $ protoc -I ../../protos --grpc_out=. --plugin=protoc-gen-grpc=`which grpc_cpp_plugin` ../../protos/route_guide.proto
  2. $ protoc -I ../../protos --cpp_out=. ../../protos/route_guide.proto

Running this command generates the following files in your current directory:

  • route_guide.pb.h, the header which declares your generated message classes
  • route_guide.pb.cc, which contains the implementation of your message classes
  • route_guide.grpc.pb.h, the header which declares your generated serviceclasses
  • route_guide.grpc.pb.cc, which contains the implementation of your serviceclasses

These contain:

  • All the protocol buffer code to populate, serialize, and retrieve our requestand response message types

  • A class called RouteGuide that contains

    • a remote interface type (or stub) for clients to call with the methodsdefined in the RouteGuide service.
    • two abstract interfaces for servers to implement, also with the methodsdefined in the RouteGuide service.

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 interface generated 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/cpp/route_guide/route_guide_server.cc.Let’s take a closer look at how it works.

Implementing RouteGuide

As you can see, our server has a RouteGuideImpl class that implements thegenerated RouteGuide::Service interface:

  1. class RouteGuideImpl final : public RouteGuide::Service {
  2. ...
  3. }

In this case we’re implementing the synchronous version of RouteGuide, whichprovides our default gRPC server behaviour. It’s also possible to implement anasynchronous interface, RouteGuide::AsyncService, which allows you to furthercustomize your server’s threading behaviour, though we won’t look at this inthis tutorial.

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. Status GetFeature(ServerContext* context, const Point* point,
  2. Feature* feature) override {
  3. feature->set_name(GetFeatureName(*point, feature_list_));
  4. feature->mutable_location()->CopyFrom(*point);
  5. return Status::OK;
  6. }

The method is passed a context object for the RPC, the client’s Point protocolbuffer request, and a Feature protocol buffer to fill in with the responseinformation. In the method we populate the Feature with the appropriateinformation, and then return with an OK status to tell gRPC that we’vefinished dealing with the RPC and that the Feature can be returned to theclient.

Note that all service methods can (and will!) be called from multiple threads atthe same time. You have to make sure that your method implementations arethread safe. In our example, featurelist is never changed afterconstruction, so it is safe by design. But if featurelist would change duringthe lifetime of the service, we would need to synchronize access to this member.

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 multipleFeatures to our client.

  1. Status ListFeatures(ServerContext* context, const Rectangle* rectangle,
  2. ServerWriter<Feature>* writer) override {
  3. auto lo = rectangle->lo();
  4. auto hi = rectangle->hi();
  5. long left = std::min(lo.longitude(), hi.longitude());
  6. long right = std::max(lo.longitude(), hi.longitude());
  7. long top = std::max(lo.latitude(), hi.latitude());
  8. long bottom = std::min(lo.latitude(), hi.latitude());
  9. for (const Feature& f : feature_list_) {
  10. if (f.location().longitude() >= left &&
  11. f.location().longitude() <= right &&
  12. f.location().latitude() >= bottom &&
  13. f.location().latitude() <= top) {
  14. writer->Write(f);
  15. }
  16. }
  17. return Status::OK;
  18. }

As you can see, instead of getting simple request and response objects in ourmethod parameters, this time we get a request object (the Rectangle in whichour client wants to find Features) and a special ServerWriter object. In themethod, we populate as many Feature objects as we need to return, writing themto the ServerWriter using its Write() method. Finally, as in our simple RPC,we return Status::OK to tell gRPC that we’ve finished writing responses.

If you look at the client-side streaming method RecordRoute you’ll see it’squite similar, except this time we get a ServerReader instead of a requestobject and a single response. We use the ServerReaders Read() method torepeatedly read in our client’s requests to a request object (in this case aPoint) until there are no more messages: the server needs to check the returnvalue of Read() after each call. If true, the stream is still good and itcan continue reading; if false the message stream has ended.

  1. while (stream->Read(&point)) {
  2. ...//process client input
  3. }

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

  1. Status RouteChat(ServerContext* context,
  2. ServerReaderWriter<RouteNote, RouteNote>* stream) override {
  3. std::vector<RouteNote> received_notes;
  4. RouteNote note;
  5. while (stream->Read(&note)) {
  6. for (const RouteNote& n : received_notes) {
  7. if (n.location().latitude() == note.location().latitude() &&
  8. n.location().longitude() == note.location().longitude()) {
  9. stream->Write(n);
  10. }
  11. }
  12. received_notes.push_back(note);
  13. }
  14. return Status::OK;
  15. }

This time we get a ServerReaderWriter that can be used to read and writemessages. The syntax for reading and writing here is exactly the same as for ourclient-streaming and server-streaming methods. Although each side will alwaysget the other’s messages in the order they were written, both the client andserver can read and write in any order — the streams operate completelyindependently.

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. void RunServer(const std::string& db_path) {
  2. std::string server_address("0.0.0.0:50051");
  3. RouteGuideImpl service(db_path);
  4. ServerBuilder builder;
  5. builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
  6. builder.RegisterService(&service);
  7. std::unique_ptr<Server> server(builder.BuildAndStart());
  8. std::cout << "Server listening on " << server_address << std::endl;
  9. server->Wait();
  10. }

As you can see, we build and start our server using a ServerBuilder. To do this, we:

  • Create an instance of our service implementation class RouteGuideImpl.
  • Create an instance of the factory ServerBuilder class.
  • Specify the address and port we want to use to listen for client requestsusing the builder’s AddListeningPort() method.
  • Register our service implementation with the builder.
  • Call BuildAndStart() on the builder to create and start an RPC server forour service.
  • Call Wait() on the server to do a blocking wait until process is killed orShutdown() is called.

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/cpp/route_guide/route_guide_client.cc.

Creating a stub

To call service methods, we first need to create a stub.

First we need to create a gRPC channel for our stub, specifying the serveraddress and port we want to connect to - in our case we’ll use no SSL:

  1. grpc::CreateChannel("localhost:50051", grpc::InsecureChannelCredentials());

Note

In order to set additional options for the channel, use the grpc::CreateCustomChannel() api with any special channel arguments - grpc::ChannelArguments.

Now we can use the channel to create our stub using the NewStub method provided in the RouteGuide class we generated from our .proto.

  1. public:
  2. RouteGuideClient(std::shared_ptr<ChannelInterface> channel,
  3. const std::string& db)
  4. : stub_(RouteGuide::NewStub(channel)) {
  5. ...
  6. }

Calling service methods

Now let’s look at how we call our service methods. Note that in this tutorialwe’re calling the blocking/synchronous versions of each method: this meansthat the RPC call waits for the server to respond, and will either return aresponse or raise an exception.

Simple RPC

Calling the simple RPC GetFeature is nearly as straightforward as calling alocal method.

  1. Point point;
  2. Feature feature;
  3. point = MakePoint(409146138, -746188906);
  4. GetOneFeature(point, &feature);
  5. ...
  6. bool GetOneFeature(const Point& point, Feature* feature) {
  7. ClientContext context;
  8. Status status = stub_->GetFeature(&context, point, feature);
  9. ...
  10. }

As you can see, we create and populate a request protocol buffer object (in ourcase Point), and create a response protocol buffer object for the server tofill in. We also create a ClientContext object for our call - you canoptionally set RPC configuration values on this object, such as deadlines,though for now we’ll use the default settings. Note that you cannot reuse thisobject between calls. Finally, we call the method on the stub, passing it thecontext, request, and response. If the method returns OK, then we can read theresponse information from the server from our response object.

  1. std::cout << "Found feature called " << feature->name() << " at "
  2. << feature->location().latitude()/kCoordFactor_ << ", "
  3. << feature->location().longitude()/kCoordFactor_ << std::endl;

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. Here’s where we call the server-sidestreaming method ListFeatures, which returns a stream of geographicalFeatures:

  1. std::unique_ptr<ClientReader<Feature> > reader(
  2. stub_->ListFeatures(&context, rect));
  3. while (reader->Read(&feature)) {
  4. std::cout << "Found feature called "
  5. << feature.name() << " at "
  6. << feature.location().latitude()/kCoordFactor_ << ", "
  7. << feature.location().longitude()/kCoordFactor_ << std::endl;
  8. }
  9. Status status = reader->Finish();

Instead of passing the method a context, request, and response, we pass it acontext and request and get a ClientReader object back. The client can use theClientReader to read the server’s responses. We use the ClientReadersRead() method to repeatedly read in the server’s responses to a responseprotocol buffer object (in this case a Feature) until there are no moremessages: the client needs to check the return value of Read() after eachcall. If true, the stream is still good and it can continue reading; iffalse the message stream has ended. Finally, we call Finish() on the streamto complete the call and get our RPC status.

The client-side streaming method RecordRoute is similar, except there we passthe method a context and response object and get back a ClientWriter.

  1. std::unique_ptr<ClientWriter<Point> > writer(
  2. stub_->RecordRoute(&context, &stats));
  3. for (int i = 0; i < kPoints; i++) {
  4. const Feature& f = feature_list_[feature_distribution(generator)];
  5. std::cout << "Visiting point "
  6. << f.location().latitude()/kCoordFactor_ << ", "
  7. << f.location().longitude()/kCoordFactor_ << std::endl;
  8. if (!writer->Write(f.location())) {
  9. // Broken stream.
  10. break;
  11. }
  12. std::this_thread::sleep_for(std::chrono::milliseconds(
  13. delay_distribution(generator)));
  14. }
  15. writer->WritesDone();
  16. Status status = writer->Finish();
  17. if (status.IsOk()) {
  18. std::cout << "Finished trip with " << stats.point_count() << " points\n"
  19. << "Passed " << stats.feature_count() << " features\n"
  20. << "Travelled " << stats.distance() << " meters\n"
  21. << "It took " << stats.elapsed_time() << " seconds"
  22. << std::endl;
  23. } else {
  24. std::cout << "RecordRoute rpc failed." << std::endl;
  25. }

Once we’ve finished writing our client’s requests to the stream using Write(),we need to call WritesDone() on the stream to let gRPC know that we’vefinished writing, then Finish() to complete the call and get our RPC status.If the status is OK, our response object that we initially passed toRecordRoute() will be populated with the server’s response.

Finally, let’s look at our bidirectional streaming RPC RouteChat(). In thiscase, we just pass a context to the method and get back a ClientReaderWriter,which we can use to both write and read messages.

  1. std::shared_ptr<ClientReaderWriter<RouteNote, RouteNote> > stream(
  2. stub_->RouteChat(&context));

The syntax for reading and writing here is exactly the same as for ourclient-streaming and server-streaming methods. Although each side will alwaysget the other’s messages in the order they were written, both the client andserver can read and write in any order — the streams operate completelyindependently.

Try it out!

Build the client and server:

  1. $ make

Run the server:

  1. $ ./route_guide_server

From a different terminal, run the client:

  1. $ ./route_guide_client