--- layout: tutorials title: gRPC Basics - C++ group: basic short: 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 the [Overview](/docs/) and are familiar with [protocol buffers](https://developers.google.com/protocol-buffers/docs/overview). Note that the example in this tutorial uses the proto3 version of the protocol buffers language: you can find out more in the [proto3 language guide](https://developers.google.com/protocol-buffers/docs/proto3) and [C++ generated code guide](https://developers.google.com/protocol-buffers/docs/reference/cpp-generated).
### Why use gRPC? Our example is a simple route mapping application that lets clients get information about features on their route, create a summary of their route, and exchange route information such as traffic updates with the server and other clients. With gRPC we can define our service once in a .proto file and implement clients and servers in any of gRPC's supported languages, which in turn can be run in environments ranging from servers inside Google to your own tablet - all the complexity of communication between different languages and environments is handled for you by gRPC. We also get all the advantages of working with protocol buffers, including efficient serialization, a simple IDL, and easy interface updating. ### Example code and setup The example code for our tutorial is in [grpc/grpc/examples/cpp/route_guide](https://github.com/grpc/grpc/tree/ {{< param grpc_release_tag >}}/examples/cpp/route_guide). To download the example, clone the `grpc` repository by running the following command: ```sh $ git clone -b {{< param grpc_release_tag >}} https://github.com/grpc/grpc ``` Then change your current directory to `examples/cpp/route_guide`: ```sh $ cd examples/cpp/route_guide ``` You also should have the relevant tools installed to generate the server and client interface code - if you don't already, follow the setup instructions in [the C++ quick start guide](/docs/quickstart/cpp). ### Defining the service Our first step (as you'll know from the [Overview](/docs/)) is to define the gRPC *service* and the method *request* and *response* types using [protocol buffers](https://developers.google.com/protocol-buffers/docs/overview). You can see the complete .proto file in [`examples/protos/route_guide.proto`](https://github.com/grpc/grpc/blob/ {{< param grpc_release_tag >}}/examples/protos/route_guide.proto). To define a service, you specify a named `service` in your .proto file: ```c service RouteGuide { ... } ``` Then you define `rpc` methods inside your service definition, specifying their request 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 stub and waits for a response to come back, just like a normal function call. ```c // Obtains the feature at a given position. rpc GetFeature(Point) returns (Feature) {} ``` - A *server-side streaming RPC* where the client sends a request to the server and gets a stream to read a sequence of messages back. The client reads from the returned stream until there are no more messages. As you can see in our example, you specify a server-side streaming method by placing the `stream` keyword before the *response* type. ```c // Obtains the Features available within the given Rectangle. Results are // streamed rather than returned at once (e.g. in a response message with a // repeated field), as the rectangle may cover a large area and contain a // huge number of features. rpc ListFeatures(Rectangle) returns (stream Feature) {} ``` - A *client-side streaming RPC* where the client writes a sequence of messages and sends them to the server, again using a provided stream. Once the client has finished writing the messages, it waits for the server to read them all and return its response. You specify a client-side streaming method by placing the `stream` keyword before the *request* type. ```c // Accepts a stream of Points on a route being traversed, returning a // RouteSummary when traversal is completed. rpc RecordRoute(stream Point) returns (RouteSummary) {} ``` - A *bidirectional streaming RPC* where both sides send a sequence of messages using a read-write stream. The two streams operate independently, so clients and servers can read and write in whatever order they like: for example, the server could wait to receive all the client messages before writing its responses, or it could alternately read a message then write a message, or some other combination of reads and writes. The order of messages in each stream is preserved. You specify this type of method by placing the `stream` keyword before both the request and the response. ```c // Accepts a stream of RouteNotes sent while a route is being traversed, // while receiving other RouteNotes (e.g. from other users). rpc RouteChat(stream RouteNote) returns (stream RouteNote) {} ``` Our .proto file also contains protocol buffer message type definitions for all the request and response types used in our service methods - for example, here's the `Point` message type: ```c // Points are represented as latitude-longitude pairs in the E7 representation // (degrees multiplied by 10**7 and rounded to the nearest integer). // Latitudes should be in the range +/- 90 degrees and longitude should be in // the range +/- 180 degrees (inclusive). message Point { int32 latitude = 1; int32 longitude = 2; } ``` ### Generating client and server code Next we need to generate the gRPC client and server interfaces from our .proto service definition. We do this using the protocol buffer compiler `protoc` with a special gRPC C++ plugin. For simplicity, we've provided a [Makefile](https://github.com/grpc/grpc/blob/ {{< param grpc_release_tag >}}/examples/cpp/route_guide/Makefile) that runs `protoc` for you with the appropriate plugin, input, and output (if you want to run this yourself, make sure you've installed protoc and followed the gRPC code [installation instructions](https://github.com/grpc/grpc/blob/ {{< param grpc_release_tag >}}/src/cpp/README.md#make) first): ```sh $ make route_guide.grpc.pb.cc route_guide.pb.cc ``` which actually runs: ```sh $ protoc -I ../../protos --grpc_out=. --plugin=protoc-gen-grpc=`which grpc_cpp_plugin` ../../protos/route_guide.proto $ 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 service classes - `route_guide.grpc.pb.cc`, which contains the implementation of your service classes These contain: - All the protocol buffer code to populate, serialize, and retrieve our request and response message types - A class called `RouteGuide` that contains - a remote interface type (or *stub*) for clients to call with the methods defined in the `RouteGuide` service. - two abstract interfaces for servers to implement, also with the methods defined in the `RouteGuide` service. ### Creating the server First let's look at how we create a `RouteGuide` server. If you're only interested in creating gRPC clients, you can skip this section and go straight to [Creating the client](#client) (though you might find it interesting anyway!). 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 the service responses. You can find our example `RouteGuide` server in [examples/cpp/route_guide/route_guide_server.cc](https://github.com/grpc/grpc/blob/ {{< param grpc_release_tag >}}/examples/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 the generated `RouteGuide::Service` interface: ```cpp class RouteGuideImpl final : public RouteGuide::Service { ... } ``` In this case we're implementing the *synchronous* version of `RouteGuide`, which provides our default gRPC server behaviour. It's also possible to implement an asynchronous interface, `RouteGuide::AsyncService`, which allows you to further customize your server's threading behaviour, though we won't look at this in this tutorial. `RouteGuideImpl` implements all our service methods. Let's look at the simplest type first, `GetFeature`, which just gets a `Point` from the client and returns the corresponding feature information from its database in a `Feature`. ```cpp Status GetFeature(ServerContext* context, const Point* point, Feature* feature) override { feature->set_name(GetFeatureName(*point, feature_list_)); feature->mutable_location()->CopyFrom(*point); return Status::OK; } ``` The method is passed a context object for the RPC, the client's `Point` protocol buffer request, and a `Feature` protocol buffer to fill in with the response information. In the method we populate the `Feature` with the appropriate information, and then `return` with an `OK` status to tell gRPC that we've finished dealing with the RPC and that the `Feature` can be returned to the client. Note that all service methods can (and will!) be called from multiple threads at the same time. You have to make sure that your method implementations are thread safe. In our example, `feature_list_` is never changed after construction, so it is safe by design. But if `feature_list_` would change during the 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 multiple `Feature`s to our client. ```cpp Status ListFeatures(ServerContext* context, const Rectangle* rectangle, ServerWriter