OLD | NEW |
(Empty) | |
| 1 #gRPC Basics: C++ |
| 2 |
| 3 This tutorial provides a basic C++ programmer's introduction to working with gRP
C. By walking through this example you'll learn how to: |
| 4 |
| 5 - Define a service in a .proto file. |
| 6 - Generate server and client code using the protocol buffer compiler. |
| 7 - Use the C++ gRPC API to write a simple client and server for your service. |
| 8 |
| 9 It assumes that you have read the [Getting started](..) guide and are familiar w
ith [protocol buffers] (https://developers.google.com/protocol-buffers/docs/over
view). Note that the example in this tutorial uses the proto3 version of the pro
tocol buffers language, which is currently in alpha release: you can find out mo
re in the [proto3 language guide](https://developers.google.com/protocol-buffers
/docs/proto3) and see the [release notes](https://github.com/google/protobuf/rel
eases) for the new version in the protocol buffers Github repository. |
| 10 |
| 11 This isn't a comprehensive guide to using gRPC in C++: more reference documentat
ion is coming soon. |
| 12 |
| 13 ## Why use gRPC? |
| 14 |
| 15 Our example is a simple route mapping application that lets clients get informat
ion 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. |
| 16 |
| 17 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 en
vironments ranging from servers inside Google to your own tablet - all the compl
exity of communication between different languages and environments is handled f
or you by gRPC. We also get all the advantages of working with protocol buffers,
including efficient serialization, a simple IDL, and easy interface updating. |
| 18 |
| 19 ## Example code and setup |
| 20 |
| 21 The example code for our tutorial is in [examples/cpp/route_guide](route_guide).
To download the example, clone this repository by running the following command
: |
| 22 ```shell |
| 23 $ git clone https://github.com/grpc/grpc.git |
| 24 ``` |
| 25 |
| 26 Then change your current directory to `examples/cpp/route_guide`: |
| 27 ```shell |
| 28 $ cd examples/cpp/route_guide |
| 29 ``` |
| 30 |
| 31 You also should have the relevant tools installed to generate the server and cli
ent interface code - if you don't already, follow the setup instructions in [gRP
C in 3 minutes](README.md). |
| 32 |
| 33 |
| 34 ## Defining the service |
| 35 |
| 36 Our first step (as you'll know from [Getting started](..) 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`](../protos/route_g
uide.proto). |
| 37 |
| 38 To define a service, you specify a named `service` in your .proto file: |
| 39 |
| 40 ``` |
| 41 service RouteGuide { |
| 42 ... |
| 43 } |
| 44 ``` |
| 45 |
| 46 Then you define `rpc` methods inside your service definition, specifying their r
equest and response types. gRPC lets you define four kinds of service method, al
l of which are used in the `RouteGuide` service: |
| 47 |
| 48 - A *simple RPC* where the client sends a request to the server using the stub a
nd waits for a response to come back, just like a normal function call. |
| 49 ``` |
| 50 // Obtains the feature at a given position. |
| 51 rpc GetFeature(Point) returns (Feature) {} |
| 52 ``` |
| 53 |
| 54 - A *server-side streaming RPC* where the client sends a request to the server a
nd 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 befo
re the *response* type. |
| 55 ``` |
| 56 // Obtains the Features available within the given Rectangle. Results are |
| 57 // streamed rather than returned at once (e.g. in a response message with a |
| 58 // repeated field), as the rectangle may cover a large area and contain a |
| 59 // huge number of features. |
| 60 rpc ListFeatures(Rectangle) returns (stream Feature) {} |
| 61 ``` |
| 62 |
| 63 - A *client-side streaming RPC* where the client writes a sequence of messages a
nd 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 retu
rn its response. You specify a client-side streaming method by placing the `stre
am` keyword before the *request* type. |
| 64 ``` |
| 65 // Accepts a stream of Points on a route being traversed, returning a |
| 66 // RouteSummary when traversal is completed. |
| 67 rpc RecordRoute(stream Point) returns (RouteSummary) {} |
| 68 ``` |
| 69 |
| 70 - A *bidirectional streaming RPC* where both sides send a sequence of messages u
sing 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 i
t could alternately read a message then write a message, or some other combinati
on of reads and writes. The order of messages in each stream is preserved. You s
pecify this type of method by placing the `stream` keyword before both the reque
st and the response. |
| 71 ``` |
| 72 // Accepts a stream of RouteNotes sent while a route is being traversed, |
| 73 // while receiving other RouteNotes (e.g. from other users). |
| 74 rpc RouteChat(stream RouteNote) returns (stream RouteNote) {} |
| 75 ``` |
| 76 |
| 77 Our .proto file also contains protocol buffer message type definitions for all t
he request and response types used in our service methods - for example, here's
the `Point` message type: |
| 78 ``` |
| 79 // Points are represented as latitude-longitude pairs in the E7 representation |
| 80 // (degrees multiplied by 10**7 and rounded to the nearest integer). |
| 81 // Latitudes should be in the range +/- 90 degrees and longitude should be in |
| 82 // the range +/- 180 degrees (inclusive). |
| 83 message Point { |
| 84 int32 latitude = 1; |
| 85 int32 longitude = 2; |
| 86 } |
| 87 ``` |
| 88 |
| 89 |
| 90 ## Generating client and server code |
| 91 |
| 92 Next we need to generate the gRPC client and server interfaces from our .proto s
ervice definition. We do this using the protocol buffer compiler `protoc` with a
special gRPC C++ plugin. |
| 93 |
| 94 For simplicity, we've provided a [makefile](route_guide/Makefile) that runs `pro
toc` 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 [ins
tallation instructions](../../INSTALL.md) first): |
| 95 |
| 96 ```shell |
| 97 $ make route_guide.grpc.pb.cc route_guide.pb.cc |
| 98 ``` |
| 99 |
| 100 which actually runs: |
| 101 |
| 102 ```shell |
| 103 $ protoc -I ../../protos --grpc_out=. --plugin=protoc-gen-grpc=`which grpc_cpp_p
lugin` ../../protos/route_guide.proto |
| 104 $ protoc -I ../../protos --cpp_out=. ../../protos/route_guide.proto |
| 105 ``` |
| 106 |
| 107 Running this command generates the following files in your current directory: |
| 108 - `route_guide.pb.h`, the header which declares your generated message classes |
| 109 - `route_guide.pb.cc`, which contains the implementation of your message classes |
| 110 - `route_guide.grpc.pb.h`, the header which declares your generated service clas
ses |
| 111 - `route_guide.grpc.pb.cc`, which contains the implementation of your service cl
asses |
| 112 |
| 113 These contain: |
| 114 - All the protocol buffer code to populate, serialize, and retrieve our request
and response message types |
| 115 - A class called `RouteGuide` that contains |
| 116 - a remote interface type (or *stub*) for clients to call with the methods de
fined in the `RouteGuide` service. |
| 117 - two abstract interfaces for servers to implement, also with the methods def
ined in the `RouteGuide` service. |
| 118 |
| 119 |
| 120 <a name="server"></a> |
| 121 ## Creating the server |
| 122 |
| 123 First let's look at how we create a `RouteGuide` server. If you're only interest
ed in creating gRPC clients, you can skip this section and go straight to [Creat
ing the client](#client) (though you might find it interesting anyway!). |
| 124 |
| 125 There are two parts to making our `RouteGuide` service do its job: |
| 126 - Implementing the service interface generated from our service definition: doin
g the actual "work" of our service. |
| 127 - Running a gRPC server to listen for requests from clients and return the servi
ce responses. |
| 128 |
| 129 You can find our example `RouteGuide` server in [route_guide/route_guide_server.
cc](route_guide/route_guide_server.cc). Let's take a closer look at how it works
. |
| 130 |
| 131 ### Implementing RouteGuide |
| 132 |
| 133 As you can see, our server has a `RouteGuideImpl` class that implements the gene
rated `RouteGuide::Service` interface: |
| 134 |
| 135 ```cpp |
| 136 class RouteGuideImpl final : public RouteGuide::Service { |
| 137 ... |
| 138 } |
| 139 ``` |
| 140 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 thi
s tutorial. |
| 141 |
| 142 `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`. |
| 143 |
| 144 ```cpp |
| 145 Status GetFeature(ServerContext* context, const Point* point, |
| 146 Feature* feature) override { |
| 147 feature->set_name(GetFeatureName(*point, feature_list_)); |
| 148 feature->mutable_location()->CopyFrom(*point); |
| 149 return Status::OK; |
| 150 } |
| 151 ``` |
| 152 |
| 153 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 in
formation. In the method we populate the `Feature` with the appropriate informat
ion, and then `return` with an `OK` status to tell gRPC that we've finished deal
ing with the RPC and that the `Feature` can be returned to the client. |
| 154 |
| 155 Now let's look at something a bit more complicated - a streaming RPC. `ListFeatu
res` is a server-side streaming RPC, so we need to send back multiple `Feature`s
to our client. |
| 156 |
| 157 ```cpp |
| 158 Status ListFeatures(ServerContext* context, const Rectangle* rectangle, |
| 159 ServerWriter<Feature>* writer) override { |
| 160 auto lo = rectangle->lo(); |
| 161 auto hi = rectangle->hi(); |
| 162 long left = std::min(lo.longitude(), hi.longitude()); |
| 163 long right = std::max(lo.longitude(), hi.longitude()); |
| 164 long top = std::max(lo.latitude(), hi.latitude()); |
| 165 long bottom = std::min(lo.latitude(), hi.latitude()); |
| 166 for (const Feature& f : feature_list_) { |
| 167 if (f.location().longitude() >= left && |
| 168 f.location().longitude() <= right && |
| 169 f.location().latitude() >= bottom && |
| 170 f.location().latitude() <= top) { |
| 171 writer->Write(f); |
| 172 } |
| 173 } |
| 174 return Status::OK; |
| 175 } |
| 176 ``` |
| 177 |
| 178 As you can see, instead of getting simple request and response objects in our me
thod parameters, this time we get a request object (the `Rectangle` in which our
client wants to find `Feature`s) and a special `ServerWriter` object. In the me
thod, we populate as many `Feature` objects as we need to return, writing them t
o 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. |
| 179 |
| 180 If you look at the client-side streaming method `RecordRoute` you'll see it's qu
ite similar, except this time we get a `ServerReader` instead of a request objec
t and a single response. We use the `ServerReader`s `Read()` method to repeatedl
y read in our client's requests to a request object (in this case a `Point`) unt
il there are no more messages: the server needs to check the return value of `Re
ad()` after each call. If `true`, the stream is still good and it can continue r
eading; if `false` the message stream has ended. |
| 181 |
| 182 ```cpp |
| 183 while (stream->Read(&point)) { |
| 184 ...//process client input |
| 185 } |
| 186 ``` |
| 187 Finally, let's look at our bidirectional streaming RPC `RouteChat()`. |
| 188 |
| 189 ```cpp |
| 190 Status RouteChat(ServerContext* context, |
| 191 ServerReaderWriter<RouteNote, RouteNote>* stream) override { |
| 192 std::vector<RouteNote> received_notes; |
| 193 RouteNote note; |
| 194 while (stream->Read(¬e)) { |
| 195 for (const RouteNote& n : received_notes) { |
| 196 if (n.location().latitude() == note.location().latitude() && |
| 197 n.location().longitude() == note.location().longitude()) { |
| 198 stream->Write(n); |
| 199 } |
| 200 } |
| 201 received_notes.push_back(note); |
| 202 } |
| 203 |
| 204 return Status::OK; |
| 205 } |
| 206 ``` |
| 207 |
| 208 This time we get a `ServerReaderWriter` that can be used to read *and* write mes
sages. The syntax for reading and writing here is exactly the same as for our cl
ient-streaming and server-streaming methods. Although each side will always get
the other's messages in the order they were written, both the client and server
can read and write in any order — the streams operate completely independently. |
| 209 |
| 210 ### Starting the server |
| 211 |
| 212 Once we've implemented all our methods, we also need to start up a gRPC server s
o that clients can actually use our service. The following snippet shows how we
do this for our `RouteGuide` service: |
| 213 |
| 214 ```cpp |
| 215 void RunServer(const std::string& db_path) { |
| 216 std::string server_address("0.0.0.0:50051"); |
| 217 RouteGuideImpl service(db_path); |
| 218 |
| 219 ServerBuilder builder; |
| 220 builder.AddListeningPort(server_address, grpc::InsecureServerCredentials()); |
| 221 builder.RegisterService(&service); |
| 222 std::unique_ptr<Server> server(builder.BuildAndStart()); |
| 223 std::cout << "Server listening on " << server_address << std::endl; |
| 224 server->Wait(); |
| 225 } |
| 226 ``` |
| 227 As you can see, we build and start our server using a `ServerBuilder`. To do thi
s, we: |
| 228 |
| 229 1. Create an instance of our service implementation class `RouteGuideImpl`. |
| 230 2. Create an instance of the factory `ServerBuilder` class. |
| 231 3. Specify the address and port we want to use to listen for client requests usi
ng the builder's `AddListeningPort()` method. |
| 232 4. Register our service implementation with the builder. |
| 233 5. Call `BuildAndStart()` on the builder to create and start an RPC server for o
ur service. |
| 234 5. Call `Wait()` on the server to do a blocking wait until process is killed or
`Shutdown()` is called. |
| 235 |
| 236 <a name="client"></a> |
| 237 ## Creating the client |
| 238 |
| 239 In this section, we'll look at creating a C++ client for our `RouteGuide` servic
e. You can see our complete example client code in [route_guide/route_guide_clie
nt.cc](route_guide/route_guide_client.cc). |
| 240 |
| 241 ### Creating a stub |
| 242 |
| 243 To call service methods, we first need to create a *stub*. |
| 244 |
| 245 First we need to create a gRPC *channel* for our stub, specifying the server add
ress and port we want to connect to without SSL: |
| 246 |
| 247 ```cpp |
| 248 grpc::CreateChannel("localhost:50051", grpc::InsecureChannelCredentials()); |
| 249 ``` |
| 250 |
| 251 Now we can use the channel to create our stub using the `NewStub` method provide
d in the `RouteGuide` class we generated from our .proto. |
| 252 |
| 253 ```cpp |
| 254 public: |
| 255 RouteGuideClient(std::shared_ptr<Channel> channel, const std::string& db) |
| 256 : stub_(RouteGuide::NewStub(channel)) { |
| 257 ... |
| 258 } |
| 259 ``` |
| 260 |
| 261 ### Calling service methods |
| 262 |
| 263 Now let's look at how we call our service methods. Note that in this tutorial we
're calling the *blocking/synchronous* versions of each method: this means that
the RPC call waits for the server to respond, and will either return a response
or raise an exception. |
| 264 |
| 265 #### Simple RPC |
| 266 |
| 267 Calling the simple RPC `GetFeature` is nearly as straightforward as calling a lo
cal method. |
| 268 |
| 269 ```cpp |
| 270 Point point; |
| 271 Feature feature; |
| 272 point = MakePoint(409146138, -746188906); |
| 273 GetOneFeature(point, &feature); |
| 274 |
| 275 ... |
| 276 |
| 277 bool GetOneFeature(const Point& point, Feature* feature) { |
| 278 ClientContext context; |
| 279 Status status = stub_->GetFeature(&context, point, feature); |
| 280 ... |
| 281 } |
| 282 ``` |
| 283 |
| 284 As you can see, we create and populate a request protocol buffer object (in our
case `Point`), and create a response protocol buffer object for the server to fi
ll in. We also create a `ClientContext` object for our call - you can optionally
set RPC configuration values on this object, such as deadlines, though for now
we'll use the default settings. Note that you cannot reuse this object between c
alls. Finally, we call the method on the stub, passing it the context, request,
and response. If the method returns `OK`, then we can read the response informat
ion from the server from our response object. |
| 285 |
| 286 ```cpp |
| 287 std::cout << "Found feature called " << feature->name() << " at " |
| 288 << feature->location().latitude()/kCoordFactor_ << ", " |
| 289 << feature->location().longitude()/kCoordFactor_ << std::endl; |
| 290 ``` |
| 291 |
| 292 #### Streaming RPCs |
| 293 |
| 294 Now let's look at our streaming methods. If you've already read [Creating the se
rver](#server) some of this may look very familiar - streaming RPCs are implemen
ted in a similar way on both sides. Here's where we call the server-side streami
ng method `ListFeatures`, which returns a stream of geographical `Feature`s: |
| 295 |
| 296 ```cpp |
| 297 std::unique_ptr<ClientReader<Feature> > reader( |
| 298 stub_->ListFeatures(&context, rect)); |
| 299 while (reader->Read(&feature)) { |
| 300 std::cout << "Found feature called " |
| 301 << feature.name() << " at " |
| 302 << feature.location().latitude()/kCoordFactor_ << ", " |
| 303 << feature.location().longitude()/kCoordFactor_ << std::endl; |
| 304 } |
| 305 Status status = reader->Finish(); |
| 306 ``` |
| 307 |
| 308 Instead of passing the method a context, request, and response, we pass it a con
text and request and get a `ClientReader` object back. The client can use the `C
lientReader` to read the server's responses. We use the `ClientReader`s `Read()`
method to repeatedly read in the server's responses to a response protocol buff
er object (in this case a `Feature`) until there are no more messages: the clien
t needs to check the return value of `Read()` after each call. If `true`, the st
ream is still good and it can continue reading; if `false` the message stream ha
s ended. Finally, we call `Finish()` on the stream to complete the call and get
our RPC status. |
| 309 |
| 310 The client-side streaming method `RecordRoute` is similar, except there we pass
the method a context and response object and get back a `ClientWriter`. |
| 311 |
| 312 ```cpp |
| 313 std::unique_ptr<ClientWriter<Point> > writer( |
| 314 stub_->RecordRoute(&context, &stats)); |
| 315 for (int i = 0; i < kPoints; i++) { |
| 316 const Feature& f = feature_list_[feature_distribution(generator)]; |
| 317 std::cout << "Visiting point " |
| 318 << f.location().latitude()/kCoordFactor_ << ", " |
| 319 << f.location().longitude()/kCoordFactor_ << std::endl; |
| 320 if (!writer->Write(f.location())) { |
| 321 // Broken stream. |
| 322 break; |
| 323 } |
| 324 std::this_thread::sleep_for(std::chrono::milliseconds( |
| 325 delay_distribution(generator))); |
| 326 } |
| 327 writer->WritesDone(); |
| 328 Status status = writer->Finish(); |
| 329 if (status.IsOk()) { |
| 330 std::cout << "Finished trip with " << stats.point_count() << " points\n" |
| 331 << "Passed " << stats.feature_count() << " features\n" |
| 332 << "Travelled " << stats.distance() << " meters\n" |
| 333 << "It took " << stats.elapsed_time() << " seconds" |
| 334 << std::endl; |
| 335 } else { |
| 336 std::cout << "RecordRoute rpc failed." << std::endl; |
| 337 } |
| 338 ``` |
| 339 |
| 340 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've finish
ed writing, then `Finish()` to complete the call and get our RPC status. If the
status is `OK`, our response object that we initially passed to `RecordRoute()`
will be populated with the server's response. |
| 341 |
| 342 Finally, let's look at our bidirectional streaming RPC `RouteChat()`. In this ca
se, we just pass a context to the method and get back a `ClientReaderWriter`, wh
ich we can use to both write and read messages. |
| 343 |
| 344 ```cpp |
| 345 std::shared_ptr<ClientReaderWriter<RouteNote, RouteNote> > stream( |
| 346 stub_->RouteChat(&context)); |
| 347 ``` |
| 348 |
| 349 The syntax for reading and writing here is exactly the same as for our client-st
reaming and server-streaming methods. Although each side will always get the oth
er's messages in the order they were written, both the client and server can rea
d and write in any order — the streams operate completely independently. |
| 350 |
| 351 ## Try it out! |
| 352 |
| 353 Build client and server: |
| 354 ```shell |
| 355 $ make |
| 356 ``` |
| 357 Run the server, which will listen on port 50051: |
| 358 ```shell |
| 359 $ ./route_guide_server |
| 360 ``` |
| 361 Run the client (in a different terminal): |
| 362 ```shell |
| 363 $ ./route_guide_client |
| 364 ``` |
| 365 |
OLD | NEW |