blob: ae84aba9163a9324f854122c965fa947cf77439a [file] [log] [blame] [view]
Lisa Carey54e0c6d2015-02-23 16:00:38 +00001#gRPC Basics: C++
2
David G. Quintas58047452016-08-11 15:40:56 -07003This tutorial provides a basic C++ programmer's introduction to working with
4gRPC. By walking through this example you'll learn how to:
Lisa Carey54e0c6d2015-02-23 16:00:38 +00005
David G. Quintas58047452016-08-11 15:40:56 -07006- Define a service in a `.proto` file.
Lisa Carey54e0c6d2015-02-23 16:00:38 +00007- Generate server and client code using the protocol buffer compiler.
8- Use the C++ gRPC API to write a simple client and server for your service.
9
David G. Quintas58047452016-08-11 15:40:56 -070010It assumes that you are familiar with
11[protocol buffers](https://developers.google.com/protocol-buffers/docs/overview).
12Note that the example in this tutorial uses the proto3 version of the protocol
13buffers language, which is currently in alpha release: you can find out more in
14the [proto3 language guide](https://developers.google.com/protocol-buffers/docs/proto3)
15and see the [release notes](https://github.com/google/protobuf/releases) for the
16new version in the protocol buffers Github repository.
Lisa Carey54e0c6d2015-02-23 16:00:38 +000017
18## Why use gRPC?
19
David G. Quintas58047452016-08-11 15:40:56 -070020Our example is a simple route mapping application that lets clients get
21information about features on their route, create a summary of their route, and
22exchange route information such as traffic updates with the server and other
23clients.
Lisa Carey54e0c6d2015-02-23 16:00:38 +000024
David G. Quintas58047452016-08-11 15:40:56 -070025With gRPC we can define our service once in a `.proto` file and implement clients
26and servers in any of gRPC's supported languages, which in turn can be run in
27environments ranging from servers inside Google to your own tablet - all the
28complexity of communication between different languages and environments is
29handled for you by gRPC. We also get all the advantages of working with protocol
30buffers, including efficient serialization, a simple IDL, and easy interface
31updating.
Lisa Carey54e0c6d2015-02-23 16:00:38 +000032
Lisa Carey54e0c6d2015-02-23 16:00:38 +000033## Example code and setup
34
David G. Quintas58047452016-08-11 15:40:56 -070035The example code for our tutorial is in [examples/cpp/route_guide](route_guide).
36You also should have the relevant tools installed to generate the server and
37client interface code - if you don't already, follow the setup instructions in
38[INSTALL.md](../../INSTALL.md).
Lisa Carey54e0c6d2015-02-23 16:00:38 +000039
40## Defining the service
41
David G. Quintas58047452016-08-11 15:40:56 -070042Our first step is to define the gRPC *service* and the method *request* and
43*response* types using
44[protocol buffers](https://developers.google.com/protocol-buffers/docs/overview).
45You can see the complete `.proto` file in
46[`examples/protos/route_guide.proto`](../protos/route_guide.proto).
Lisa Carey54e0c6d2015-02-23 16:00:38 +000047
David G. Quintas58047452016-08-11 15:40:56 -070048To define a service, you specify a named `service` in your `.proto` file:
Lisa Carey54e0c6d2015-02-23 16:00:38 +000049
David G. Quintas58047452016-08-11 15:40:56 -070050```protobuf
Lisa Carey54e0c6d2015-02-23 16:00:38 +000051service RouteGuide {
52 ...
53}
54```
55
David G. Quintas58047452016-08-11 15:40:56 -070056Then you define `rpc` methods inside your service definition, specifying their
57request and response types. gRPC lets you define four kinds of service method,
58all of which are used in the `RouteGuide` service:
Lisa Carey54e0c6d2015-02-23 16:00:38 +000059
David G. Quintas58047452016-08-11 15:40:56 -070060- A *simple RPC* where the client sends a request to the server using the stub
61 and waits for a response to come back, just like a normal function call.
62
63```protobuf
Yang Gaode0c6532015-02-24 15:52:22 -080064 // Obtains the feature at a given position.
Lisa Carey54e0c6d2015-02-23 16:00:38 +000065 rpc GetFeature(Point) returns (Feature) {}
66```
67
David G. Quintas58047452016-08-11 15:40:56 -070068- A *server-side streaming RPC* where the client sends a request to the server
69 and gets a stream to read a sequence of messages back. The client reads from
70 the returned stream until there are no more messages. As you can see in our
71 example, you specify a server-side streaming method by placing the `stream`
72 keyword before the *response* type.
73
74```protobuf
Lisa Carey54e0c6d2015-02-23 16:00:38 +000075 // Obtains the Features available within the given Rectangle. Results are
76 // streamed rather than returned at once (e.g. in a response message with a
77 // repeated field), as the rectangle may cover a large area and contain a
78 // huge number of features.
79 rpc ListFeatures(Rectangle) returns (stream Feature) {}
80```
81
David G. Quintas58047452016-08-11 15:40:56 -070082- A *client-side streaming RPC* where the client writes a sequence of messages
83 and sends them to the server, again using a provided stream. Once the client
84 has finished writing the messages, it waits for the server to read them all
85 and return its response. You specify a client-side streaming method by placing
86 the `stream` keyword before the *request* type.
87
88```protobuf
Lisa Carey54e0c6d2015-02-23 16:00:38 +000089 // Accepts a stream of Points on a route being traversed, returning a
90 // RouteSummary when traversal is completed.
91 rpc RecordRoute(stream Point) returns (RouteSummary) {}
92```
93
David G. Quintas58047452016-08-11 15:40:56 -070094- A *bidirectional streaming RPC* where both sides send a sequence of messages
95 using a read-write stream. The two streams operate independently, so clients
96 and servers can read and write in whatever order they like: for example, the
97 server could wait to receive all the client messages before writing its
98 responses, or it could alternately read a message then write a message, or
99 some other combination of reads and writes. The order of messages in each
100 stream is preserved. You specify this type of method by placing the `stream`
101 keyword before both the request and the response.
102
103```protobuf
Lisa Carey450d1122015-02-23 16:05:25 +0000104 // Accepts a stream of RouteNotes sent while a route is being traversed,
105 // while receiving other RouteNotes (e.g. from other users).
106 rpc RouteChat(stream RouteNote) returns (stream RouteNote) {}
Lisa Carey54e0c6d2015-02-23 16:00:38 +0000107```
108
David G. Quintas58047452016-08-11 15:40:56 -0700109Our `.proto` file also contains protocol buffer message type definitions for all
110the request and response types used in our service methods - for example, here's
111the `Point` message type:
112
113```protobuf
Lisa Carey450d1122015-02-23 16:05:25 +0000114// Points are represented as latitude-longitude pairs in the E7 representation
115// (degrees multiplied by 10**7 and rounded to the nearest integer).
116// Latitudes should be in the range +/- 90 degrees and longitude should be in
117// the range +/- 180 degrees (inclusive).
118message Point {
119 int32 latitude = 1;
120 int32 longitude = 2;
121}
Lisa Carey54e0c6d2015-02-23 16:00:38 +0000122```
123
Lisa Carey54e0c6d2015-02-23 16:00:38 +0000124## Generating client and server code
125
David G. Quintas58047452016-08-11 15:40:56 -0700126Next we need to generate the gRPC client and server interfaces from our `.proto`
127service definition. We do this using the protocol buffer compiler `protoc` with
128a special gRPC C++ plugin.
Lisa Carey7a219662015-02-23 16:42:21 +0000129
David Garcia Quintasc61b1d32016-08-11 16:15:41 -0700130For simplicity, we've provided a [Makefile](route_guide/Makefile) that runs
David G. Quintas58047452016-08-11 15:40:56 -0700131`protoc` for you with the appropriate plugin, input, and output (if you want to
132run this yourself, make sure you've installed protoc and followed the gRPC code
133[installation instructions](../../INSTALL.md) first):
Lisa Carey7a219662015-02-23 16:42:21 +0000134
135```shell
Nicolas "Pixel" Nobleb6413de2015-04-10 00:24:09 +0200136$ make route_guide.grpc.pb.cc route_guide.pb.cc
Lisa Carey7a219662015-02-23 16:42:21 +0000137```
138
139which actually runs:
140
Yang Gaocdbb60c2015-02-24 15:01:36 -0800141```shell
Nicolas "Pixel" Nobleb6413de2015-04-10 00:24:09 +0200142$ protoc -I ../../protos --grpc_out=. --plugin=protoc-gen-grpc=`which grpc_cpp_plugin` ../../protos/route_guide.proto
143$ protoc -I ../../protos --cpp_out=. ../../protos/route_guide.proto
Yang Gaocdbb60c2015-02-24 15:01:36 -0800144```
Lisa Carey7a219662015-02-23 16:42:21 +0000145
LisaFC25ffbd82015-02-25 14:12:39 +0000146Running this command generates the following files in your current directory:
Nicolas "Pixel" Nobleb6413de2015-04-10 00:24:09 +0200147- `route_guide.pb.h`, the header which declares your generated message classes
148- `route_guide.pb.cc`, which contains the implementation of your message classes
David G. Quintas58047452016-08-11 15:40:56 -0700149- `route_guide.grpc.pb.h`, the header which declares your generated service
150 classes
151- `route_guide.grpc.pb.cc`, which contains the implementation of your service
152 classes
Lisa Carey7a219662015-02-23 16:42:21 +0000153
Lisa Carey453eca32015-02-23 16:58:19 +0000154These contain:
David G. Quintas58047452016-08-11 15:40:56 -0700155- All the protocol buffer code to populate, serialize, and retrieve our request
156 and response message types
Lisa Carey14184fa2015-02-24 16:56:30 +0000157- A class called `RouteGuide` that contains
David G. Quintas58047452016-08-11 15:40:56 -0700158 - a remote interface type (or *stub*) for clients to call with the methods
159 defined in the `RouteGuide` service.
160 - two abstract interfaces for servers to implement, also with the methods
161 defined in the `RouteGuide` service.
Lisa Carey54e0c6d2015-02-23 16:00:38 +0000162
163
Lisa Carey14184fa2015-02-24 16:56:30 +0000164<a name="server"></a>
Lisa Carey54e0c6d2015-02-23 16:00:38 +0000165## Creating the server
166
David G. Quintas58047452016-08-11 15:40:56 -0700167First let's look at how we create a `RouteGuide` server. If you're only
168interested in creating gRPC clients, you can skip this section and go straight
169to [Creating the client](#client) (though you might find it interesting
170anyway!).
Lisa Carey54e0c6d2015-02-23 16:00:38 +0000171
Lisa Carey14184fa2015-02-24 16:56:30 +0000172There are two parts to making our `RouteGuide` service do its job:
David G. Quintas58047452016-08-11 15:40:56 -0700173- Implementing the service interface generated from our service definition:
174 doing the actual "work" of our service.
175- Running a gRPC server to listen for requests from clients and return the
176 service responses.
Lisa Carey54e0c6d2015-02-23 16:00:38 +0000177
David G. Quintas58047452016-08-11 15:40:56 -0700178You can find our example `RouteGuide` server in
179[route_guide/route_guide_server.cc](route_guide/route_guide_server.cc). Let's
180take a closer look at how it works.
Lisa Carey54e0c6d2015-02-23 16:00:38 +0000181
Lisa Carey14184fa2015-02-24 16:56:30 +0000182### Implementing RouteGuide
183
David G. Quintas58047452016-08-11 15:40:56 -0700184As you can see, our server has a `RouteGuideImpl` class that implements the
185generated `RouteGuide::Service` interface:
Lisa Carey14184fa2015-02-24 16:56:30 +0000186
187```cpp
188class RouteGuideImpl final : public RouteGuide::Service {
189...
190}
191```
David G. Quintas58047452016-08-11 15:40:56 -0700192In this case we're implementing the *synchronous* version of `RouteGuide`, which
193provides our default gRPC server behaviour. It's also possible to implement an
194asynchronous interface, `RouteGuide::AsyncService`, which allows you to further
195customize your server's threading behaviour, though we won't look at this in
196this tutorial.
Lisa Carey14184fa2015-02-24 16:56:30 +0000197
David G. Quintas58047452016-08-11 15:40:56 -0700198`RouteGuideImpl` implements all our service methods. Let's look at the simplest
199type first, `GetFeature`, which just gets a `Point` from the client and returns
200the corresponding feature information from its database in a `Feature`.
Lisa Carey14184fa2015-02-24 16:56:30 +0000201
202```cpp
203 Status GetFeature(ServerContext* context, const Point* point,
204 Feature* feature) override {
205 feature->set_name(GetFeatureName(*point, feature_list_));
206 feature->mutable_location()->CopyFrom(*point);
207 return Status::OK;
208 }
209```
210
David G. Quintas58047452016-08-11 15:40:56 -0700211The method is passed a context object for the RPC, the client's `Point` protocol
212buffer request, and a `Feature` protocol buffer to fill in with the response
213information. In the method we populate the `Feature` with the appropriate
214information, and then `return` with an `OK` status to tell gRPC that we've
215finished dealing with the RPC and that the `Feature` can be returned to the
216client.
Lisa Carey14184fa2015-02-24 16:56:30 +0000217
David G. Quintas58047452016-08-11 15:40:56 -0700218Now let's look at something a bit more complicated - a streaming RPC.
219`ListFeatures` is a server-side streaming RPC, so we need to send back multiple
220`Feature`s to our client.
Lisa Carey14184fa2015-02-24 16:56:30 +0000221
222```cpp
David G. Quintas58047452016-08-11 15:40:56 -0700223Status ListFeatures(ServerContext* context, const Rectangle* rectangle,
224 ServerWriter<Feature>* writer) override {
225 auto lo = rectangle->lo();
226 auto hi = rectangle->hi();
227 long left = std::min(lo.longitude(), hi.longitude());
228 long right = std::max(lo.longitude(), hi.longitude());
229 long top = std::max(lo.latitude(), hi.latitude());
230 long bottom = std::min(lo.latitude(), hi.latitude());
231 for (const Feature& f : feature_list_) {
232 if (f.location().longitude() >= left &&
233 f.location().longitude() <= right &&
234 f.location().latitude() >= bottom &&
235 f.location().latitude() <= top) {
236 writer->Write(f);
Lisa Carey14184fa2015-02-24 16:56:30 +0000237 }
Lisa Carey14184fa2015-02-24 16:56:30 +0000238 }
David G. Quintas58047452016-08-11 15:40:56 -0700239 return Status::OK;
240}
Lisa Carey14184fa2015-02-24 16:56:30 +0000241```
242
David G. Quintas58047452016-08-11 15:40:56 -0700243As you can see, instead of getting simple request and response objects in our
244method parameters, this time we get a request object (the `Rectangle` in which
245our client wants to find `Feature`s) and a special `ServerWriter` object. In the
246method, we populate as many `Feature` objects as we need to return, writing them
247to the `ServerWriter` using its `Write()` method. Finally, as in our simple RPC,
248we `return Status::OK` to tell gRPC that we've finished writing responses.
Lisa Carey14184fa2015-02-24 16:56:30 +0000249
David G. Quintas58047452016-08-11 15:40:56 -0700250If you look at the client-side streaming method `RecordRoute` you'll see it's
251quite similar, except this time we get a `ServerReader` instead of a request
252object and a single response. We use the `ServerReader`s `Read()` method to
253repeatedly read in our client's requests to a request object (in this case a
254`Point`) until there are no more messages: the server needs to check the return
255value of `Read()` after each call. If `true`, the stream is still good and it
256can continue reading; if `false` the message stream has ended.
Lisa Carey14184fa2015-02-24 16:56:30 +0000257
258```cpp
259while (stream->Read(&point)) {
260 ...//process client input
261}
262```
263Finally, let's look at our bidirectional streaming RPC `RouteChat()`.
264
265```cpp
266 Status RouteChat(ServerContext* context,
267 ServerReaderWriter<RouteNote, RouteNote>* stream) override {
268 std::vector<RouteNote> received_notes;
269 RouteNote note;
270 while (stream->Read(&note)) {
271 for (const RouteNote& n : received_notes) {
272 if (n.location().latitude() == note.location().latitude() &&
273 n.location().longitude() == note.location().longitude()) {
274 stream->Write(n);
275 }
276 }
277 received_notes.push_back(note);
278 }
279
280 return Status::OK;
281 }
282```
283
David G. Quintas58047452016-08-11 15:40:56 -0700284This time we get a `ServerReaderWriter` that can be used to read *and* write
285messages. The syntax for reading and writing here is exactly the same as for our
286client-streaming and server-streaming methods. Although each side will always
287get the other's messages in the order they were written, both the client and
288server can read and write in any order the streams operate completely
289independently.
Lisa Carey14184fa2015-02-24 16:56:30 +0000290
291### Starting the server
292
David G. Quintas58047452016-08-11 15:40:56 -0700293Once we've implemented all our methods, we also need to start up a gRPC server
294so that clients can actually use our service. The following snippet shows how we
295do this for our `RouteGuide` service:
Lisa Carey14184fa2015-02-24 16:56:30 +0000296
297```cpp
298void RunServer(const std::string& db_path) {
299 std::string server_address("0.0.0.0:50051");
300 RouteGuideImpl service(db_path);
301
302 ServerBuilder builder;
Nicolas "Pixel" Noble2afb2702015-03-23 23:44:31 +0100303 builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
Lisa Carey14184fa2015-02-24 16:56:30 +0000304 builder.RegisterService(&service);
305 std::unique_ptr<Server> server(builder.BuildAndStart());
306 std::cout << "Server listening on " << server_address << std::endl;
Yang Gao44e98222015-02-24 16:06:02 -0800307 server->Wait();
Lisa Carey14184fa2015-02-24 16:56:30 +0000308}
309```
310As you can see, we build and start our server using a `ServerBuilder`. To do this, we:
311
3121. Create an instance of our service implementation class `RouteGuideImpl`.
David G. Quintas58047452016-08-11 15:40:56 -07003131. Create an instance of the factory `ServerBuilder` class.
3141. Specify the address and port we want to use to listen for client requests
315 using the builder's `AddListeningPort()` method.
3161. Register our service implementation with the builder.
3171. Call `BuildAndStart()` on the builder to create and start an RPC server for
318 our service.
3191. Call `Wait()` on the server to do a blocking wait until process is killed or
320 `Shutdown()` is called.
Lisa Carey14184fa2015-02-24 16:56:30 +0000321
322<a name="client"></a>
Lisa Carey54e0c6d2015-02-23 16:00:38 +0000323## Creating the client
324
David G. Quintas58047452016-08-11 15:40:56 -0700325In this section, we'll look at creating a C++ client for our `RouteGuide`
326service. You can see our complete example client code in
327[route_guide/route_guide_client.cc](route_guide/route_guide_client.cc).
Lisa Carey14184fa2015-02-24 16:56:30 +0000328
329### Creating a stub
330
331To call service methods, we first need to create a *stub*.
332
David G. Quintas58047452016-08-11 15:40:56 -0700333First we need to create a gRPC *channel* for our stub, specifying the server
334address and port we want to connect to without SSL:
Lisa Carey14184fa2015-02-24 16:56:30 +0000335
336```cpp
Julien Boeuf8c48a2a2015-10-17 22:23:02 -0700337grpc::CreateChannel("localhost:50051", grpc::InsecureChannelCredentials());
Lisa Carey14184fa2015-02-24 16:56:30 +0000338```
339
David G. Quintas58047452016-08-11 15:40:56 -0700340Now we can use the channel to create our stub using the `NewStub` method
341provided in the `RouteGuide` class we generated from our `.proto`.
Lisa Carey14184fa2015-02-24 16:56:30 +0000342
343```cpp
David G. Quintas58047452016-08-11 15:40:56 -0700344public:
345 RouteGuideClient(std::shared_ptr<Channel> channel, const std::string& db)
346 : stub_(RouteGuide::NewStub(channel)) {
347 ...
348 }
Lisa Carey14184fa2015-02-24 16:56:30 +0000349```
350
351### Calling service methods
352
David G. Quintas58047452016-08-11 15:40:56 -0700353Now let's look at how we call our service methods. Note that in this tutorial
354we're calling the *blocking/synchronous* versions of each method: this means
355that the RPC call waits for the server to respond, and will either return a
356response or raise an exception.
Lisa Careyfea91522015-02-24 18:07:45 +0000357
Lisa Carey88a49f62015-02-24 18:09:38 +0000358#### Simple RPC
359
David G. Quintas58047452016-08-11 15:40:56 -0700360Calling the simple RPC `GetFeature` is nearly as straightforward as calling a
361local method.
Lisa Carey14184fa2015-02-24 16:56:30 +0000362
363```cpp
364 Point point;
365 Feature feature;
366 point = MakePoint(409146138, -746188906);
367 GetOneFeature(point, &feature);
368
369...
370
371 bool GetOneFeature(const Point& point, Feature* feature) {
372 ClientContext context;
373 Status status = stub_->GetFeature(&context, point, feature);
374 ...
375 }
376```
377
David G. Quintas58047452016-08-11 15:40:56 -0700378As you can see, we create and populate a request protocol buffer object (in our
379case `Point`), and create a response protocol buffer object for the server to
380fill in. We also create a `ClientContext` object for our call - you can
381optionally set RPC configuration values on this object, such as deadlines,
382though for now we'll use the default settings. Note that you cannot reuse this
383object between calls. Finally, we call the method on the stub, passing it the
384context, request, and response. If the method returns `OK`, then we can read the
385response information from the server from our response object.
Lisa Carey14184fa2015-02-24 16:56:30 +0000386
387```cpp
David G. Quintas58047452016-08-11 15:40:56 -0700388std::cout << "Found feature called " << feature->name() << " at "
389 << feature->location().latitude()/kCoordFactor_ << ", "
390 << feature->location().longitude()/kCoordFactor_ << std::endl;
Lisa Carey14184fa2015-02-24 16:56:30 +0000391```
392
Lisa Carey88a49f62015-02-24 18:09:38 +0000393#### Streaming RPCs
394
David G. Quintas58047452016-08-11 15:40:56 -0700395Now let's look at our streaming methods. If you've already read [Creating the
396server](#server) some of this may look very familiar - streaming RPCs are
397implemented in a similar way on both sides. Here's where we call the server-side
398streaming method `ListFeatures`, which returns a stream of geographical
399`Feature`s:
Lisa Carey54e0c6d2015-02-23 16:00:38 +0000400
Lisa Careyfea91522015-02-24 18:07:45 +0000401```cpp
David G. Quintas58047452016-08-11 15:40:56 -0700402std::unique_ptr<ClientReader<Feature> > reader(
403 stub_->ListFeatures(&context, rect));
404while (reader->Read(&feature)) {
405 std::cout << "Found feature called "
406 << feature.name() << " at "
407 << feature.location().latitude()/kCoordFactor_ << ", "
408 << feature.location().longitude()/kCoordFactor_ << std::endl;
409}
410Status status = reader->Finish();
Lisa Careyfea91522015-02-24 18:07:45 +0000411```
412
David G. Quintas58047452016-08-11 15:40:56 -0700413Instead of passing the method a context, request, and response, we pass it a
414context and request and get a `ClientReader` object back. The client can use the
415`ClientReader` to read the server's responses. We use the `ClientReader`s
416`Read()` method to repeatedly read in the server's responses to a response
417protocol buffer object (in this case a `Feature`) until there are no more
418messages: the client needs to check the return value of `Read()` after each
419call. If `true`, the stream is still good and it can continue reading; if
420`false` the message stream has ended. Finally, we call `Finish()` on the stream
421to complete the call and get our RPC status.
Lisa Careyfea91522015-02-24 18:07:45 +0000422
David G. Quintas58047452016-08-11 15:40:56 -0700423The client-side streaming method `RecordRoute` is similar, except there we pass
424the method a context and response object and get back a `ClientWriter`.
Lisa Careyfea91522015-02-24 18:07:45 +0000425
426```cpp
427 std::unique_ptr<ClientWriter<Point> > writer(
428 stub_->RecordRoute(&context, &stats));
429 for (int i = 0; i < kPoints; i++) {
430 const Feature& f = feature_list_[feature_distribution(generator)];
431 std::cout << "Visiting point "
432 << f.location().latitude()/kCoordFactor_ << ", "
433 << f.location().longitude()/kCoordFactor_ << std::endl;
434 if (!writer->Write(f.location())) {
435 // Broken stream.
436 break;
437 }
438 std::this_thread::sleep_for(std::chrono::milliseconds(
439 delay_distribution(generator)));
440 }
441 writer->WritesDone();
442 Status status = writer->Finish();
443 if (status.IsOk()) {
444 std::cout << "Finished trip with " << stats.point_count() << " points\n"
445 << "Passed " << stats.feature_count() << " features\n"
446 << "Travelled " << stats.distance() << " meters\n"
447 << "It took " << stats.elapsed_time() << " seconds"
448 << std::endl;
449 } else {
450 std::cout << "RecordRoute rpc failed." << std::endl;
451 }
452```
453
David G. Quintas58047452016-08-11 15:40:56 -0700454Once we've finished writing our client's requests to the stream using `Write()`,
455we need to call `WritesDone()` on the stream to let gRPC know that we've
456finished writing, then `Finish()` to complete the call and get our RPC status.
457If the status is `OK`, our response object that we initially passed to
458`RecordRoute()` will be populated with the server's response.
Lisa Careyfea91522015-02-24 18:07:45 +0000459
David G. Quintas58047452016-08-11 15:40:56 -0700460Finally, let's look at our bidirectional streaming RPC `RouteChat()`. In this
461case, we just pass a context to the method and get back a `ClientReaderWriter`,
462which we can use to both write and read messages.
Lisa Careyfea91522015-02-24 18:07:45 +0000463
464```cpp
David G. Quintas58047452016-08-11 15:40:56 -0700465std::shared_ptr<ClientReaderWriter<RouteNote, RouteNote> > stream(
466 stub_->RouteChat(&context));
Lisa Careyfea91522015-02-24 18:07:45 +0000467```
468
David G. Quintas58047452016-08-11 15:40:56 -0700469The syntax for reading and writing here is exactly the same as for our
470client-streaming and server-streaming methods. Although each side will always
471get the other's messages in the order they were written, both the client and
472server can read and write in any order — the streams operate completely
473independently.
Lisa Carey54e0c6d2015-02-23 16:00:38 +0000474
Lisa Carey14184fa2015-02-24 16:56:30 +0000475## Try it out!
476
Yang Gao9a2ff4f2015-02-24 16:13:02 -0800477Build client and server:
478```shell
479$ make
480```
481Run the server, which will listen on port 50051:
482```shell
483$ ./route_guide_server
484```
485Run the client (in a different terminal):
486```shell
487$ ./route_guide_client
488```