aboutsummaryrefslogtreecommitdiffhomepage
path: root/examples/cpp
diff options
context:
space:
mode:
Diffstat (limited to 'examples/cpp')
-rw-r--r--examples/cpp/README.md65
-rw-r--r--examples/cpp/cpptutorial.md365
-rw-r--r--examples/cpp/helloworld/Makefile119
-rw-r--r--examples/cpp/helloworld/README.md260
-rw-r--r--examples/cpp/helloworld/greeter_async_client.cc98
-rw-r--r--examples/cpp/helloworld/greeter_async_server.cc136
-rw-r--r--examples/cpp/helloworld/greeter_client.cc85
-rw-r--r--examples/cpp/helloworld/greeter_server.cc78
-rw-r--r--examples/cpp/route_guide/Makefile113
-rw-r--r--examples/cpp/route_guide/helper.cc178
-rw-r--r--examples/cpp/route_guide/helper.h50
-rw-r--r--examples/cpp/route_guide/route_guide_client.cc252
-rw-r--r--examples/cpp/route_guide/route_guide_db.json601
-rw-r--r--examples/cpp/route_guide/route_guide_server.cc202
14 files changed, 2602 insertions, 0 deletions
diff --git a/examples/cpp/README.md b/examples/cpp/README.md
new file mode 100644
index 0000000000..70418b4425
--- /dev/null
+++ b/examples/cpp/README.md
@@ -0,0 +1,65 @@
+#gRPC in 3 minutes (C++)
+
+## Installation
+
+To install gRPC on your system, follow the instructions here:
+[https://github.com/grpc/grpc/blob/master/INSTALL](https://github.com/grpc/grpc/blob/master/INSTALL).
+
+## Hello C++ gRPC!
+
+Here's how to build and run the C++ implementation of the [Hello World](examples/protos/helloworld.proto) example used in [Getting started](https://github.com/grpc/grpc/tree/master/examples).
+
+The example code for this and our other examples lives in the `examples`
+directory. Clone this repository to your local machine by running the
+following command:
+
+
+```sh
+$ git clone https://github.com/grpc/grpc.git
+```
+
+Change your current directory to examples/cpp/helloworld
+
+```sh
+$ cd examples/cpp/helloworld/
+```
+
+
+### Generating gRPC code
+
+To generate the client and server side interfaces:
+
+```sh
+$ make helloworld.grpc.pb.cc helloworld.pb.cc
+```
+Which internally invokes the proto-compiler as:
+
+```sh
+$ protoc -I ../../protos/ --grpc_out=. --plugin=protoc-gen-grpc=grpc_cpp_plugin ../../protos/helloworld.proto
+$ protoc -I ../../protos/ --cpp_out=. ../../protos/helloworld.proto
+```
+
+### Client and server implementations
+
+The client implementation is at [greeter_client.cc](examples/cpp/helloworld/greeter_client.cc).
+
+The server implementation is at [greeter_server.cc](examples/cpp/helloworld/greeter_server.cc).
+
+### Try it!
+Build client and server:
+```sh
+$ make
+```
+Run the server, which will listen on port 50051:
+```sh
+$ ./greeter_server
+```
+Run the client (in a different terminal):
+```sh
+$ ./greeter_client
+```
+If things go smoothly, you will see the "Greeter received: Hello world" in the client side output.
+
+## Tutorial
+
+You can find a more detailed tutorial in [gRPC Basics: C++](examples/cpp/cpptutorial.md)
diff --git a/examples/cpp/cpptutorial.md b/examples/cpp/cpptutorial.md
new file mode 100644
index 0000000000..22be42d500
--- /dev/null
+++ b/examples/cpp/cpptutorial.md
@@ -0,0 +1,365 @@
+#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 the [Getting started](https://github.com/grpc/grpc/tree/master/examples) guide 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, which is currently in alpha release: you can find out more in the [proto3 language guide](https://developers.google.com/protocol-buffers/docs/proto3) and see the [release notes](https://github.com/google/protobuf/releases) for the new version in the protocol buffers Github repository.
+
+This isn't a comprehensive guide to using gRPC in C++: more reference documentation is coming soon.
+
+## 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 [examples/cpp/route_guide](examples/cpp/route_guide). To download the example, clone this repository by running the following command:
+```shell
+$ git clone https://github.com/grpc/grpc.git
+```
+
+Then change your current directory to `examples/cpp/route_guide`:
+```shell
+$ 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](examples/cpp).
+
+
+## Defining the service
+
+Our first step (as you'll know from [Getting started](examples/) 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`](examples/protos/route_guide.proto).
+
+To define a service, you specify a named `service` in your .proto file:
+
+```
+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.
+```
+ // 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.
+```
+ // 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.
+```
+ // 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.
+```
+ // 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:
+```
+// 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](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/master/INSTALL) first):
+
+```shell
+$ make route_guide.grpc.pb.cc route_guide.pb.cc
+```
+
+which actually runs:
+
+```shell
+$ 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.
+
+
+<a name="server"></a>
+## 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](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.
+
+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<Feature>* writer) override {
+ auto lo = rectangle->lo();
+ auto hi = rectangle->hi();
+ long left = std::min(lo.longitude(), hi.longitude());
+ long right = std::max(lo.longitude(), hi.longitude());
+ long top = std::max(lo.latitude(), hi.latitude());
+ long bottom = std::min(lo.latitude(), hi.latitude());
+ for (const Feature& f : feature_list_) {
+ if (f.location().longitude() >= left &&
+ f.location().longitude() <= right &&
+ f.location().latitude() >= bottom &&
+ f.location().latitude() <= top) {
+ writer->Write(f);
+ }
+ }
+ return Status::OK;
+ }
+```
+
+As you can see, instead of getting simple request and response objects in our method 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 method, we populate as many `Feature` objects as we need to return, writing them to 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's quite similar, except this time we get a `ServerReader` instead of a request object and a single response. We use the `ServerReader`s `Read()` method to repeatedly read in our client's requests to a request object (in this case a `Point`) until there are no more messages: the server needs to check the return value of `Read()` after each call. If `true`, the stream is still good and it can continue reading; if `false` the message stream has ended.
+
+```cpp
+while (stream->Read(&point)) {
+ ...//process client input
+}
+```
+Finally, let's look at our bidirectional streaming RPC `RouteChat()`.
+
+```cpp
+ Status RouteChat(ServerContext* context,
+ ServerReaderWriter<RouteNote, RouteNote>* stream) override {
+ std::vector<RouteNote> received_notes;
+ RouteNote note;
+ while (stream->Read(&note)) {
+ for (const RouteNote& n : received_notes) {
+ if (n.location().latitude() == note.location().latitude() &&
+ n.location().longitude() == note.location().longitude()) {
+ stream->Write(n);
+ }
+ }
+ received_notes.push_back(note);
+ }
+
+ return Status::OK;
+ }
+```
+
+This time we get a `ServerReaderWriter` that can be used to read *and* write messages. The syntax for reading and writing here is exactly the same as for our client-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.
+
+### Starting the server
+
+Once we've implemented all our methods, we also need to start up a gRPC server so that clients can actually use our service. The following snippet shows how we do this for our `RouteGuide` service:
+
+```cpp
+void RunServer(const std::string& db_path) {
+ std::string server_address("0.0.0.0:50051");
+ RouteGuideImpl service(db_path);
+
+ ServerBuilder builder;
+ builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
+ builder.RegisterService(&service);
+ std::unique_ptr<Server> server(builder.BuildAndStart());
+ std::cout << "Server listening on " << server_address << std::endl;
+ server->Wait();
+}
+```
+As you can see, we build and start our server using a `ServerBuilder`. To do this, we:
+
+1. Create an instance of our service implementation class `RouteGuideImpl`.
+2. Create an instance of the factory `ServerBuilder` class.
+3. Specify the address and port we want to use to listen for client requests using the builder's `AddListeningPort()` method.
+4. Register our service implementation with the builder.
+5. Call `BuildAndStart()` on the builder to create and start an RPC server for our service.
+5. Call `Wait()` on the server to do a blocking wait until process is killed or `Shutdown()` is called.
+
+<a name="client"></a>
+## Creating the client
+
+In this section, we'll look at creating a C++ client for our `RouteGuide` service. You can see our complete example client code in [examples/cpp/route_guide/route_guide_client.cc](examples/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 server address and port we want to connect to and any special channel arguments - in our case we'll use the default `ChannelArguments` and no SSL:
+
+```cpp
+grpc::CreateChannel("localhost:50051", grpc::InsecureCredentials(), 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.
+
+```cpp
+ public:
+ RouteGuideClient(std::shared_ptr<Channel> channel, const std::string& db)
+ : stub_(RouteGuide::NewStub(channel)) {
+ ...
+ }
+```
+
+### Calling service methods
+
+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.
+
+#### Simple RPC
+
+Calling the simple RPC `GetFeature` is nearly as straightforward as calling a local method.
+
+```cpp
+ Point point;
+ Feature feature;
+ point = MakePoint(409146138, -746188906);
+ GetOneFeature(point, &feature);
+
+...
+
+ bool GetOneFeature(const Point& point, Feature* feature) {
+ ClientContext context;
+ Status status = stub_->GetFeature(&context, point, feature);
+ ...
+ }
+```
+
+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 fill 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 calls. 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 information from the server from our response object.
+
+```cpp
+ std::cout << "Found feature called " << feature->name() << " at "
+ << feature->location().latitude()/kCoordFactor_ << ", "
+ << feature->location().longitude()/kCoordFactor_ << std::endl;
+```
+
+#### Streaming RPCs
+
+Now let's look at our streaming methods. If you've already read [Creating the server](#server) some of this may look very familiar - streaming RPCs are implemented in a similar way on both sides. Here's where we call the server-side streaming method `ListFeatures`, which returns a stream of geographical `Feature`s:
+
+```cpp
+ std::unique_ptr<ClientReader<Feature> > reader(
+ stub_->ListFeatures(&context, rect));
+ while (reader->Read(&feature)) {
+ std::cout << "Found feature called "
+ << feature.name() << " at "
+ << feature.location().latitude()/kCoordFactor_ << ", "
+ << feature.location().longitude()/kCoordFactor_ << std::endl;
+ }
+ Status status = reader->Finish();
+```
+
+Instead of passing the method a context, request, and response, we pass it a context and request and get a `ClientReader` object back. The client can use the `ClientReader` 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 buffer object (in this case a `Feature`) until there are no more messages: the client needs to check the return value of `Read()` after each call. If `true`, the stream is still good and it can continue reading; if `false` the message stream has ended. Finally, we call `Finish()` on the stream to complete the call and get our RPC status.
+
+The client-side streaming method `RecordRoute` is similar, except there we pass the method a context and response object and get back a `ClientWriter`.
+
+```cpp
+ std::unique_ptr<ClientWriter<Point> > writer(
+ stub_->RecordRoute(&context, &stats));
+ for (int i = 0; i < kPoints; i++) {
+ const Feature& f = feature_list_[feature_distribution(generator)];
+ std::cout << "Visiting point "
+ << f.location().latitude()/kCoordFactor_ << ", "
+ << f.location().longitude()/kCoordFactor_ << std::endl;
+ if (!writer->Write(f.location())) {
+ // Broken stream.
+ break;
+ }
+ std::this_thread::sleep_for(std::chrono::milliseconds(
+ delay_distribution(generator)));
+ }
+ writer->WritesDone();
+ Status status = writer->Finish();
+ if (status.IsOk()) {
+ std::cout << "Finished trip with " << stats.point_count() << " points\n"
+ << "Passed " << stats.feature_count() << " features\n"
+ << "Travelled " << stats.distance() << " meters\n"
+ << "It took " << stats.elapsed_time() << " seconds"
+ << std::endl;
+ } else {
+ std::cout << "RecordRoute rpc failed." << std::endl;
+ }
+```
+
+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 finished 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.
+
+Finally, let's look at our bidirectional streaming RPC `RouteChat()`. In this case, we just pass a context to the method and get back a `ClientReaderWriter`, which we can use to both write and read messages.
+
+```cpp
+ std::shared_ptr<ClientReaderWriter<RouteNote, RouteNote> > stream(
+ stub_->RouteChat(&context));
+```
+
+The syntax for reading and writing here is exactly the same as for our client-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.
+
+## Try it out!
+
+Build client and server:
+```shell
+$ make
+```
+Run the server, which will listen on port 50051:
+```shell
+$ ./route_guide_server
+```
+Run the client (in a different terminal):
+```shell
+$ ./route_guide_client
+```
+
diff --git a/examples/cpp/helloworld/Makefile b/examples/cpp/helloworld/Makefile
new file mode 100644
index 0000000000..f2093afa05
--- /dev/null
+++ b/examples/cpp/helloworld/Makefile
@@ -0,0 +1,119 @@
+#
+# Copyright 2015, Google Inc.
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are
+# met:
+#
+# * Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+# * Redistributions in binary form must reproduce the above
+# copyright notice, this list of conditions and the following disclaimer
+# in the documentation and/or other materials provided with the
+# distribution.
+# * Neither the name of Google Inc. nor the names of its
+# contributors may be used to endorse or promote products derived from
+# this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#
+
+CXX = g++
+CPPFLAGS += -I/usr/local/include -pthread
+CXXFLAGS += -std=c++11
+LDFLAGS += -L/usr/local/lib -lgrpc++_unsecure -lgrpc -lgpr -lprotobuf -lpthread -ldl
+PROTOC = protoc
+GRPC_CPP_PLUGIN = grpc_cpp_plugin
+GRPC_CPP_PLUGIN_PATH ?= `which $(GRPC_CPP_PLUGIN)`
+
+PROTOS_PATH = ../../protos
+
+vpath %.proto $(PROTOS_PATH)
+
+all: system-check greeter_client greeter_server greeter_async_client greeter_async_server
+
+greeter_client: helloworld.pb.o helloworld.grpc.pb.o greeter_client.o
+ $(CXX) $^ $(LDFLAGS) -o $@
+
+greeter_server: helloworld.pb.o helloworld.grpc.pb.o greeter_server.o
+ $(CXX) $^ $(LDFLAGS) -o $@
+
+greeter_async_client: helloworld.pb.o helloworld.grpc.pb.o greeter_async_client.o
+ $(CXX) $^ $(LDFLAGS) -o $@
+
+greeter_async_server: helloworld.pb.o helloworld.grpc.pb.o greeter_async_server.o
+ $(CXX) $^ $(LDFLAGS) -o $@
+
+%.grpc.pb.cc: %.proto
+ $(PROTOC) -I $(PROTOS_PATH) --grpc_out=. --plugin=protoc-gen-grpc=$(GRPC_CPP_PLUGIN_PATH) $<
+
+%.pb.cc: %.proto
+ $(PROTOC) -I $(PROTOS_PATH) --cpp_out=. $<
+
+clean:
+ rm -f *.o *.pb.cc *.pb.h greeter_client greeter_server greeter_async_client greeter_async_server
+
+
+# The following is to test your system and ensure a smoother experience.
+# They are by no means necessary to actually compile a grpc-enabled software.
+
+PROTOC_CMD = which $(PROTOC)
+PROTOC_CHECK_CMD = $(PROTOC) --version | grep -q libprotoc.3
+PLUGIN_CHECK_CMD = which $(GRPC_CPP_PLUGIN)
+HAS_PROTOC = $(shell $(PROTOC_CMD) > /dev/null && echo true || echo false)
+ifeq ($(HAS_PROTOC),true)
+HAS_VALID_PROTOC = $(shell $(PROTOC_CHECK_CMD) 2> /dev/null && echo true || echo false)
+endif
+HAS_PLUGIN = $(shell $(PLUGIN_CHECK_CMD) > /dev/null && echo true || echo false)
+
+SYSTEM_OK = false
+ifeq ($(HAS_VALID_PROTOC),true)
+ifeq ($(HAS_PLUGIN),true)
+SYSTEM_OK = true
+endif
+endif
+
+system-check:
+ifneq ($(HAS_VALID_PROTOC),true)
+ @echo " DEPENDENCY ERROR"
+ @echo
+ @echo "You don't have protoc 3.0.0 installed in your path."
+ @echo "Please install Google protocol buffers 3.0.0 and its compiler."
+ @echo "You can find it here:"
+ @echo
+ @echo " https://github.com/google/protobuf/releases/tag/v3.0.0-alpha-1"
+ @echo
+ @echo "Here is what I get when trying to evaluate your version of protoc:"
+ @echo
+ -$(PROTOC) --version
+ @echo
+ @echo
+endif
+ifneq ($(HAS_PLUGIN),true)
+ @echo " DEPENDENCY ERROR"
+ @echo
+ @echo "You don't have the grpc c++ protobuf plugin installed in your path."
+ @echo "Please install grpc. You can find it here:"
+ @echo
+ @echo " https://github.com/grpc/grpc"
+ @echo
+ @echo "Here is what I get when trying to detect if you have the plugin:"
+ @echo
+ -which $(GRPC_CPP_PLUGIN)
+ @echo
+ @echo
+endif
+ifneq ($(SYSTEM_OK),true)
+ @false
+endif
diff --git a/examples/cpp/helloworld/README.md b/examples/cpp/helloworld/README.md
new file mode 100644
index 0000000000..641aadd52d
--- /dev/null
+++ b/examples/cpp/helloworld/README.md
@@ -0,0 +1,260 @@
+# gRPC C++ Hello World Tutorial
+
+### Install gRPC
+Make sure you have installed gRPC on your system. Follow the instructions here:
+[https://github.com/grpc/grpc/blob/master/INSTALL](https://github.com/grpc/grpc/blob/master/INSTALL).
+
+### Get the tutorial source code
+
+The example code for this and our other examples lives in the `examples`
+directory. Clone this repository to your local machine by running the
+following command:
+
+
+```sh
+$ git clone https://github.com/grpc/grpc.git
+```
+
+Change your current directory to examples/cpp/helloworld
+
+```sh
+$ cd examples/cpp/helloworld/
+```
+
+### Defining a service
+
+The first step in creating our example is to define a *service*: an RPC
+service specifies the methods that can be called remotely with their parameters
+and return types. As you saw in the
+[overview](#protocolbuffers) above, gRPC does this using [protocol
+buffers](https://developers.google.com/protocol-buffers/docs/overview). We
+use the protocol buffers interface definition language (IDL) to define our
+service methods, and define the parameters and return
+types as protocol buffer message types. Both the client and the
+server use interface code generated from the service definition.
+
+Here's our example service definition, defined using protocol buffers IDL in
+[helloworld.proto](examples/protos/helloworld.proto). The `Greeting`
+service has one method, `hello`, that lets the server receive a single
+`HelloRequest`
+message from the remote client containing the user's name, then send back
+a greeting in a single `HelloReply`. This is the simplest type of RPC you
+can specify in gRPC - we'll look at some other types later in this document.
+
+```
+syntax = "proto3";
+
+option java_package = "ex.grpc";
+
+package helloworld;
+
+// The greeting service definition.
+service Greeter {
+ // Sends a greeting
+ rpc SayHello (HelloRequest) returns (HelloReply) {}
+}
+
+// The request message containing the user's name.
+message HelloRequest {
+ string name = 1;
+}
+
+// The response message containing the greetings
+message HelloReply {
+ string message = 1;
+}
+
+```
+
+<a name="generating"></a>
+### Generating gRPC code
+
+Once we've defined our service, we use the protocol buffer compiler
+`protoc` to generate the special client and server code we need to create
+our application. The generated code contains both stub code for clients to
+use and an abstract interface for servers to implement, both with the method
+defined in our `Greeting` service.
+
+To generate the client and server side interfaces:
+
+```sh
+$ make helloworld.grpc.pb.cc helloworld.pb.cc
+```
+Which internally invokes the proto-compiler as:
+
+```sh
+$ protoc -I ../../protos/ --grpc_out=. --plugin=protoc-gen-grpc=grpc_cpp_plugin ../../protos/helloworld.proto
+$ protoc -I ../../protos/ --cpp_out=. ../../protos/helloworld.proto
+```
+
+### Writing a client
+
+- Create a channel. A channel is a logical connection to an endpoint. A gRPC
+ channel can be created with the target address, credentials to use and
+ arguments as follows
+
+ ```
+ auto channel = CreateChannel("localhost:50051", InsecureCredentials(), ChannelArguments());
+ ```
+
+- Create a stub. A stub implements the rpc methods of a service and in the
+ generated code, a method is provided to created a stub with a channel:
+
+ ```
+ auto stub = helloworld::Greeter::NewStub(channel);
+ ```
+
+- Make a unary rpc, with `ClientContext` and request/response proto messages.
+
+ ```
+ ClientContext context;
+ HelloRequest request;
+ request.set_name("hello");
+ HelloReply reply;
+ Status status = stub->SayHello(&context, request, &reply);
+ ```
+
+- Check returned status and response.
+
+ ```
+ if (status.ok()) {
+ // check reply.message()
+ } else {
+ // rpc failed.
+ }
+ ```
+
+For a working example, refer to [greeter_client.cc](examples/cpp/helloworld/greeter_client.cc).
+
+### Writing a server
+
+- Implement the service interface
+
+ ```
+ class GreeterServiceImpl final : public Greeter::Service {
+ Status SayHello(ServerContext* context, const HelloRequest* request,
+ HelloReply* reply) override {
+ std::string prefix("Hello ");
+ reply->set_message(prefix + request->name());
+ return Status::OK;
+ }
+ };
+
+ ```
+
+- Build a server exporting the service
+
+ ```
+ GreeterServiceImpl service;
+ ServerBuilder builder;
+ builder.AddListeningPort("0.0.0.0:50051", grpc::InsecureServerCredentials());
+ builder.RegisterService(&service);
+ std::unique_ptr<Server> server(builder.BuildAndStart());
+ ```
+
+For a working example, refer to [greeter_server.cc](examples/cpp/helloworld/greeter_server.cc).
+
+### Writing asynchronous client and server
+
+gRPC uses `CompletionQueue` API for asynchronous operations. The basic work flow
+is
+- bind a `CompletionQueue` to a rpc call
+- do something like a read or write, present with a unique `void*` tag
+- call `CompletionQueue::Next` to wait for operations to complete. If a tag
+ appears, it indicates that the corresponding operation is complete.
+
+#### Async client
+
+The channel and stub creation code is the same as the sync client.
+
+- Initiate the rpc and create a handle for the rpc. Bind the rpc to a
+ `CompletionQueue`.
+
+ ```
+ CompletionQueue cq;
+ auto rpc = stub->AsyncSayHello(&context, request, &cq);
+ ```
+
+- Ask for reply and final status, with a unique tag
+
+ ```
+ Status status;
+ rpc->Finish(&reply, &status, (void*)1);
+ ```
+
+- Wait for the completion queue to return the next tag. The reply and status are
+ ready once the tag passed into the corresponding `Finish()` call is returned.
+
+ ```
+ void* got_tag;
+ bool ok = false;
+ cq.Next(&got_tag, &ok);
+ if (ok && got_tag == (void*)1) {
+ // check reply and status
+ }
+ ```
+
+For a working example, refer to [greeter_async_client.cc](examples/cpp/helloworld/greeter_async_client.cc).
+
+#### Async server
+
+The server implementation requests a rpc call with a tag and then wait for the
+completion queue to return the tag. The basic flow is
+
+- Build a server exporting the async service
+
+ ```
+ helloworld::Greeter::AsyncService service;
+ ServerBuilder builder;
+ builder.AddListeningPort("0.0.0.0:50051", InsecureServerCredentials());
+ builder.RegisterAsyncService(&service);
+ auto cq = builder.AddCompletionQueue();
+ auto server = builder.BuildAndStart();
+ ```
+
+- Request one rpc
+
+ ```
+ ServerContext context;
+ HelloRequest request;
+ ServerAsyncResponseWriter<HelloReply> responder;
+ service.RequestSayHello(&context, &request, &responder, &cq, &cq, (void*)1);
+ ```
+
+- Wait for the completion queue to return the tag. The context, request and
+ responder are ready once the tag is retrieved.
+
+ ```
+ HelloReply reply;
+ Status status;
+ void* got_tag;
+ bool ok = false;
+ cq.Next(&got_tag, &ok);
+ if (ok && got_tag == (void*)1) {
+ // set reply and status
+ responder.Finish(reply, status, (void*)2);
+ }
+ ```
+
+- Wait for the completion queue to return the tag. The rpc is finished when the
+ tag is back.
+
+ ```
+ void* got_tag;
+ bool ok = false;
+ cq.Next(&got_tag, &ok);
+ if (ok && got_tag == (void*)2) {
+ // clean up
+ }
+ ```
+
+To handle multiple rpcs, the async server creates an object `CallData` to
+maintain the state of each rpc and use the address of it as the unique tag. For
+simplicity the server only uses one completion queue for all events, and runs a
+main loop in `HandleRpcs` to query the queue.
+
+For a working example, refer to [greeter_async_server.cc](examples/cpp/helloworld/greeter_async_server.cc).
+
+
+
+
diff --git a/examples/cpp/helloworld/greeter_async_client.cc b/examples/cpp/helloworld/greeter_async_client.cc
new file mode 100644
index 0000000000..d99f89b135
--- /dev/null
+++ b/examples/cpp/helloworld/greeter_async_client.cc
@@ -0,0 +1,98 @@
+/*
+ *
+ * Copyright 2015, Google Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include <iostream>
+#include <memory>
+#include <string>
+
+#include <grpc/grpc.h>
+#include <grpc/support/log.h>
+#include <grpc++/channel.h>
+#include <grpc++/client_context.h>
+#include <grpc++/completion_queue.h>
+#include <grpc++/create_channel.h>
+#include <grpc++/credentials.h>
+#include "helloworld.grpc.pb.h"
+
+using grpc::Channel;
+using grpc::ChannelArguments;
+using grpc::ClientAsyncResponseReader;
+using grpc::ClientContext;
+using grpc::CompletionQueue;
+using grpc::Status;
+using helloworld::HelloRequest;
+using helloworld::HelloReply;
+using helloworld::Greeter;
+
+class GreeterClient {
+ public:
+ explicit GreeterClient(std::shared_ptr<Channel> channel)
+ : stub_(Greeter::NewStub(channel)) {}
+
+ std::string SayHello(const std::string& user) {
+ HelloRequest request;
+ request.set_name(user);
+ HelloReply reply;
+ ClientContext context;
+ CompletionQueue cq;
+ Status status;
+
+ std::unique_ptr<ClientAsyncResponseReader<HelloReply> > rpc(
+ stub_->AsyncSayHello(&context, request, &cq));
+ rpc->Finish(&reply, &status, (void*)1);
+ void* got_tag;
+ bool ok = false;
+ cq.Next(&got_tag, &ok);
+ GPR_ASSERT(ok);
+ GPR_ASSERT(got_tag == (void*)1);
+
+ if (status.ok()) {
+ return reply.message();
+ } else {
+ return "Rpc failed";
+ }
+ }
+
+ private:
+ std::unique_ptr<Greeter::Stub> stub_;
+};
+
+int main(int argc, char** argv) {
+ GreeterClient greeter(grpc::CreateChannel(
+ "localhost:50051", grpc::InsecureCredentials(), ChannelArguments()));
+ std::string user("world");
+ std::string reply = greeter.SayHello(user);
+ std::cout << "Greeter received: " << reply << std::endl;
+
+ return 0;
+}
diff --git a/examples/cpp/helloworld/greeter_async_server.cc b/examples/cpp/helloworld/greeter_async_server.cc
new file mode 100644
index 0000000000..b8a0dbf0e2
--- /dev/null
+++ b/examples/cpp/helloworld/greeter_async_server.cc
@@ -0,0 +1,136 @@
+/*
+ *
+ * Copyright 2015, Google Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include <memory>
+#include <iostream>
+#include <string>
+#include <thread>
+
+#include <grpc/grpc.h>
+#include <grpc/support/log.h>
+#include <grpc++/completion_queue.h>
+#include <grpc++/server.h>
+#include <grpc++/server_builder.h>
+#include <grpc++/server_context.h>
+#include <grpc++/server_credentials.h>
+#include "helloworld.grpc.pb.h"
+
+using grpc::Server;
+using grpc::ServerAsyncResponseWriter;
+using grpc::ServerBuilder;
+using grpc::ServerContext;
+using grpc::ServerCompletionQueue;
+using grpc::Status;
+using helloworld::HelloRequest;
+using helloworld::HelloReply;
+using helloworld::Greeter;
+
+class ServerImpl final {
+ public:
+ ~ServerImpl() {
+ server_->Shutdown();
+ cq_->Shutdown();
+ }
+
+ // There is no shutdown handling in this code.
+ void Run() {
+ std::string server_address("0.0.0.0:50051");
+
+ ServerBuilder builder;
+ builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
+ builder.RegisterAsyncService(&service_);
+ cq_ = builder.AddCompletionQueue();
+ server_ = builder.BuildAndStart();
+ std::cout << "Server listening on " << server_address << std::endl;
+
+ HandleRpcs();
+ }
+
+ private:
+ class CallData {
+ public:
+ CallData(Greeter::AsyncService* service, ServerCompletionQueue* cq)
+ : service_(service), cq_(cq), responder_(&ctx_), status_(CREATE) {
+ Proceed();
+ }
+
+ void Proceed() {
+ if (status_ == CREATE) {
+ service_->RequestSayHello(&ctx_, &request_, &responder_, cq_, cq_,
+ this);
+ status_ = PROCESS;
+ } else if (status_ == PROCESS) {
+ new CallData(service_, cq_);
+ std::string prefix("Hello ");
+ reply_.set_message(prefix + request_.name());
+ responder_.Finish(reply_, Status::OK, this);
+ status_ = FINISH;
+ } else {
+ delete this;
+ }
+ }
+
+ private:
+ Greeter::AsyncService* service_;
+ ServerCompletionQueue* cq_;
+ ServerContext ctx_;
+ HelloRequest request_;
+ HelloReply reply_;
+ ServerAsyncResponseWriter<HelloReply> responder_;
+ enum CallStatus { CREATE, PROCESS, FINISH };
+ CallStatus status_;
+ };
+
+ // This can be run in multiple threads if needed.
+ void HandleRpcs() {
+ new CallData(&service_, cq_.get());
+ void* tag;
+ bool ok;
+ while (true) {
+ cq_->Next(&tag, &ok);
+ GPR_ASSERT(ok);
+ static_cast<CallData*>(tag)->Proceed();
+ }
+ }
+
+ std::unique_ptr<ServerCompletionQueue> cq_;
+ Greeter::AsyncService service_;
+ std::unique_ptr<Server> server_;
+};
+
+int main(int argc, char** argv) {
+ ServerImpl server;
+ server.Run();
+
+ return 0;
+}
diff --git a/examples/cpp/helloworld/greeter_client.cc b/examples/cpp/helloworld/greeter_client.cc
new file mode 100644
index 0000000000..dd0358ac95
--- /dev/null
+++ b/examples/cpp/helloworld/greeter_client.cc
@@ -0,0 +1,85 @@
+/*
+ *
+ * Copyright 2015, Google Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include <iostream>
+#include <memory>
+#include <string>
+
+#include <grpc/grpc.h>
+#include <grpc++/channel.h>
+#include <grpc++/client_context.h>
+#include <grpc++/create_channel.h>
+#include <grpc++/credentials.h>
+#include "helloworld.grpc.pb.h"
+
+using grpc::Channel;
+using grpc::ChannelArguments;
+using grpc::ClientContext;
+using grpc::Status;
+using helloworld::HelloRequest;
+using helloworld::HelloReply;
+using helloworld::Greeter;
+
+class GreeterClient {
+ public:
+ GreeterClient(std::shared_ptr<Channel> channel)
+ : stub_(Greeter::NewStub(channel)) {}
+
+ std::string SayHello(const std::string& user) {
+ HelloRequest request;
+ request.set_name(user);
+ HelloReply reply;
+ ClientContext context;
+
+ Status status = stub_->SayHello(&context, request, &reply);
+ if (status.ok()) {
+ return reply.message();
+ } else {
+ return "Rpc failed";
+ }
+ }
+
+ private:
+ std::unique_ptr<Greeter::Stub> stub_;
+};
+
+int main(int argc, char** argv) {
+ GreeterClient greeter(
+ grpc::CreateChannel("localhost:50051", grpc::InsecureCredentials(),
+ ChannelArguments()));
+ std::string user("world");
+ std::string reply = greeter.SayHello(user);
+ std::cout << "Greeter received: " << reply << std::endl;
+
+ return 0;
+}
diff --git a/examples/cpp/helloworld/greeter_server.cc b/examples/cpp/helloworld/greeter_server.cc
new file mode 100644
index 0000000000..c1efdf563c
--- /dev/null
+++ b/examples/cpp/helloworld/greeter_server.cc
@@ -0,0 +1,78 @@
+/*
+ *
+ * Copyright 2015, Google Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include <iostream>
+#include <memory>
+#include <string>
+
+#include <grpc/grpc.h>
+#include <grpc++/server.h>
+#include <grpc++/server_builder.h>
+#include <grpc++/server_context.h>
+#include <grpc++/server_credentials.h>
+#include "helloworld.grpc.pb.h"
+
+using grpc::Server;
+using grpc::ServerBuilder;
+using grpc::ServerContext;
+using grpc::Status;
+using helloworld::HelloRequest;
+using helloworld::HelloReply;
+using helloworld::Greeter;
+
+class GreeterServiceImpl final : public Greeter::Service {
+ Status SayHello(ServerContext* context, const HelloRequest* request,
+ HelloReply* reply) override {
+ std::string prefix("Hello ");
+ reply->set_message(prefix + request->name());
+ return Status::OK;
+ }
+};
+
+void RunServer() {
+ std::string server_address("0.0.0.0:50051");
+ GreeterServiceImpl service;
+
+ ServerBuilder builder;
+ builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
+ builder.RegisterService(&service);
+ std::unique_ptr<Server> server(builder.BuildAndStart());
+ std::cout << "Server listening on " << server_address << std::endl;
+ server->Wait();
+}
+
+int main(int argc, char** argv) {
+ RunServer();
+
+ return 0;
+}
diff --git a/examples/cpp/route_guide/Makefile b/examples/cpp/route_guide/Makefile
new file mode 100644
index 0000000000..b906177af3
--- /dev/null
+++ b/examples/cpp/route_guide/Makefile
@@ -0,0 +1,113 @@
+#
+# Copyright 2015, Google Inc.
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are
+# met:
+#
+# * Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+# * Redistributions in binary form must reproduce the above
+# copyright notice, this list of conditions and the following disclaimer
+# in the documentation and/or other materials provided with the
+# distribution.
+# * Neither the name of Google Inc. nor the names of its
+# contributors may be used to endorse or promote products derived from
+# this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#
+
+CXX = g++
+CPPFLAGS += -I/usr/local/include -pthread
+CXXFLAGS += -std=c++11
+LDFLAGS += -L/usr/local/lib -lgrpc++_unsecure -lgrpc -lgpr -lprotobuf -lpthread -ldl
+PROTOC = protoc
+GRPC_CPP_PLUGIN = grpc_cpp_plugin
+GRPC_CPP_PLUGIN_PATH ?= `which $(GRPC_CPP_PLUGIN)`
+
+PROTOS_PATH = ../../protos
+
+vpath %.proto $(PROTOS_PATH)
+
+all: system-check route_guide_client route_guide_server
+
+route_guide_client: route_guide.pb.o route_guide.grpc.pb.o route_guide_client.o helper.o
+ $(CXX) $^ $(LDFLAGS) -o $@
+
+route_guide_server: route_guide.pb.o route_guide.grpc.pb.o route_guide_server.o helper.o
+ $(CXX) $^ $(LDFLAGS) -o $@
+
+%.grpc.pb.cc: %.proto
+ $(PROTOC) -I $(PROTOS_PATH) --grpc_out=. --plugin=protoc-gen-grpc=$(GRPC_CPP_PLUGIN_PATH) $<
+
+%.pb.cc: %.proto
+ $(PROTOC) -I $(PROTOS_PATH) --cpp_out=. $<
+
+clean:
+ rm -f *.o *.pb.cc *.pb.h route_guide_client route_guide_server
+
+
+# The following is to test your system and ensure a smoother experience.
+# They are by no means necessary to actually compile a grpc-enabled software.
+
+PROTOC_CMD = which $(PROTOC)
+PROTOC_CHECK_CMD = $(PROTOC) --version | grep -q libprotoc.3
+PLUGIN_CHECK_CMD = which $(GRPC_CPP_PLUGIN)
+HAS_PROTOC = $(shell $(PROTOC_CMD) > /dev/null && echo true || echo false)
+ifeq ($(HAS_PROTOC),true)
+HAS_VALID_PROTOC = $(shell $(PROTOC_CHECK_CMD) 2> /dev/null && echo true || echo false)
+endif
+HAS_PLUGIN = $(shell $(PLUGIN_CHECK_CMD) > /dev/null && echo true || echo false)
+
+SYSTEM_OK = false
+ifeq ($(HAS_VALID_PROTOC),true)
+ifeq ($(HAS_PLUGIN),true)
+SYSTEM_OK = true
+endif
+endif
+
+system-check:
+ifneq ($(HAS_VALID_PROTOC),true)
+ @echo " DEPENDENCY ERROR"
+ @echo
+ @echo "You don't have protoc 3.0.0 installed in your path."
+ @echo "Please install Google protocol buffers 3.0.0 and its compiler."
+ @echo "You can find it here:"
+ @echo
+ @echo " https://github.com/google/protobuf/releases/tag/v3.0.0-alpha-1"
+ @echo
+ @echo "Here is what I get when trying to evaluate your version of protoc:"
+ @echo
+ -$(PROTOC) --version
+ @echo
+ @echo
+endif
+ifneq ($(HAS_PLUGIN),true)
+ @echo " DEPENDENCY ERROR"
+ @echo
+ @echo "You don't have the grpc c++ protobuf plugin installed in your path."
+ @echo "Please install grpc. You can find it here:"
+ @echo
+ @echo " https://github.com/grpc/grpc"
+ @echo
+ @echo "Here is what I get when trying to detect if you have the plugin:"
+ @echo
+ -which $(GRPC_CPP_PLUGIN)
+ @echo
+ @echo
+endif
+ifneq ($(SYSTEM_OK),true)
+ @false
+endif
diff --git a/examples/cpp/route_guide/helper.cc b/examples/cpp/route_guide/helper.cc
new file mode 100644
index 0000000000..c2415afdf7
--- /dev/null
+++ b/examples/cpp/route_guide/helper.cc
@@ -0,0 +1,178 @@
+/*
+ *
+ * Copyright 2015, Google Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include <algorithm>
+#include <cctype>
+#include <fstream>
+#include <iostream>
+#include <sstream>
+#include <string>
+#include <vector>
+#include "route_guide.grpc.pb.h"
+
+namespace examples {
+
+std::string GetDbFileContent(int argc, char** argv) {
+ std::string db_path;
+ std::string arg_str("--db_path");
+ if (argc > 1) {
+ std::string argv_1 = argv[1];
+ size_t start_position = argv_1.find(arg_str);
+ if (start_position != std::string::npos) {
+ start_position += arg_str.size();
+ if (argv_1[start_position] == ' ' ||
+ argv_1[start_position] == '=') {
+ db_path = argv_1.substr(start_position + 1);
+ }
+ }
+ } else {
+ db_path = "route_guide_db.json";
+ }
+ std::ifstream db_file(db_path);
+ if (!db_file.is_open()) {
+ std::cout << "Failed to open " << db_path << std::endl;
+ return "";
+ }
+ std::stringstream db;
+ db << db_file.rdbuf();
+ return db.str();
+}
+
+// A simple parser for the json db file. It requires the db file to have the
+// exact form of [{"location": { "latitude": 123, "longitude": 456}, "name":
+// "the name can be empty" }, { ... } ... The spaces will be stripped.
+class Parser {
+ public:
+ explicit Parser(const std::string& db) : db_(db) {
+ // Remove all spaces.
+ db_.erase(
+ std::remove_if(db_.begin(), db_.end(), isspace),
+ db_.end());
+ if (!Match("[")) {
+ SetFailedAndReturnFalse();
+ }
+ }
+
+ bool Finished() {
+ return current_ >= db_.size();
+ }
+
+ bool TryParseOne(Feature* feature) {
+ if (failed_ || Finished() || !Match("{")) {
+ return SetFailedAndReturnFalse();
+ }
+ if (!Match(location_) || !Match("{") || !Match(latitude_)) {
+ return SetFailedAndReturnFalse();
+ }
+ long temp = 0;
+ ReadLong(&temp);
+ feature->mutable_location()->set_latitude(temp);
+ if (!Match(",") || !Match(longitude_)) {
+ return SetFailedAndReturnFalse();
+ }
+ ReadLong(&temp);
+ feature->mutable_location()->set_longitude(temp);
+ if (!Match("},") || !Match(name_) || !Match("\"")) {
+ return SetFailedAndReturnFalse();
+ }
+ size_t name_start = current_;
+ while (current_ != db_.size() && db_[current_++] != '"') {
+ }
+ if (current_ == db_.size()) {
+ return SetFailedAndReturnFalse();
+ }
+ feature->set_name(db_.substr(name_start, current_-name_start-1));
+ if (!Match("},")) {
+ if (db_[current_ - 1] == ']' && current_ == db_.size()) {
+ return true;
+ }
+ return SetFailedAndReturnFalse();
+ }
+ return true;
+ }
+
+ private:
+
+ bool SetFailedAndReturnFalse() {
+ failed_ = true;
+ return false;
+ }
+
+ bool Match(const std::string& prefix) {
+ bool eq = db_.substr(current_, prefix.size()) == prefix;
+ current_ += prefix.size();
+ return eq;
+ }
+
+ void ReadLong(long* l) {
+ size_t start = current_;
+ while (current_ != db_.size() && db_[current_] != ',' && db_[current_] != '}') {
+ current_++;
+ }
+ // It will throw an exception if fails.
+ *l = std::stol(db_.substr(start, current_ - start));
+ }
+
+ bool failed_ = false;
+ std::string db_;
+ size_t current_ = 0;
+ const std::string location_ = "\"location\":";
+ const std::string latitude_ = "\"latitude\":";
+ const std::string longitude_ = "\"longitude\":";
+ const std::string name_ = "\"name\":";
+};
+
+void ParseDb(const std::string& db, std::vector<Feature>* feature_list) {
+ feature_list->clear();
+ std::string db_content(db);
+ db_content.erase(
+ std::remove_if(db_content.begin(), db_content.end(), isspace),
+ db_content.end());
+
+ Parser parser(db_content);
+ Feature feature;
+ while (!parser.Finished()) {
+ feature_list->push_back(Feature());
+ if (!parser.TryParseOne(&feature_list->back())) {
+ std::cout << "Error parsing the db file";
+ feature_list->clear();
+ break;
+ }
+ }
+ std::cout << "DB parsed, loaded " << feature_list->size()
+ << " features." << std::endl;
+}
+
+
+} // namespace examples
+
diff --git a/examples/cpp/route_guide/helper.h b/examples/cpp/route_guide/helper.h
new file mode 100644
index 0000000000..65c93c1d34
--- /dev/null
+++ b/examples/cpp/route_guide/helper.h
@@ -0,0 +1,50 @@
+/*
+ *
+ * Copyright 2015, Google Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#ifndef GRPC_COMMON_CPP_ROUTE_GUIDE_HELPER_H_
+#define GRPC_COMMON_CPP_ROUTE_GUIDE_HELPER_H_
+
+#include <string>
+#include <vector>
+
+namespace examples {
+class Feature;
+
+std::string GetDbFileContent(int argc, char** argv);
+
+void ParseDb(const std::string& db, std::vector<Feature>* feature_list);
+
+} // namespace examples
+
+#endif // GRPC_COMMON_CPP_ROUTE_GUIDE_HELPER_H_
+
diff --git a/examples/cpp/route_guide/route_guide_client.cc b/examples/cpp/route_guide/route_guide_client.cc
new file mode 100644
index 0000000000..814def27f3
--- /dev/null
+++ b/examples/cpp/route_guide/route_guide_client.cc
@@ -0,0 +1,252 @@
+/*
+ *
+ * Copyright 2015, Google Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include <chrono>
+#include <iostream>
+#include <memory>
+#include <random>
+#include <string>
+#include <thread>
+
+#include <grpc/grpc.h>
+#include <grpc++/channel.h>
+#include <grpc++/client_context.h>
+#include <grpc++/create_channel.h>
+#include <grpc++/credentials.h>
+#include "helper.h"
+#include "route_guide.grpc.pb.h"
+
+using grpc::Channel;
+using grpc::ChannelArguments;
+using grpc::ClientContext;
+using grpc::ClientReader;
+using grpc::ClientReaderWriter;
+using grpc::ClientWriter;
+using grpc::Status;
+using examples::Point;
+using examples::Feature;
+using examples::Rectangle;
+using examples::RouteSummary;
+using examples::RouteNote;
+using examples::RouteGuide;
+
+Point MakePoint(long latitude, long longitude) {
+ Point p;
+ p.set_latitude(latitude);
+ p.set_longitude(longitude);
+ return p;
+}
+
+Feature MakeFeature(const std::string& name,
+ long latitude, long longitude) {
+ Feature f;
+ f.set_name(name);
+ f.mutable_location()->CopyFrom(MakePoint(latitude, longitude));
+ return f;
+}
+
+RouteNote MakeRouteNote(const std::string& message,
+ long latitude, long longitude) {
+ RouteNote n;
+ n.set_message(message);
+ n.mutable_location()->CopyFrom(MakePoint(latitude, longitude));
+ return n;
+}
+
+class RouteGuideClient {
+ public:
+ RouteGuideClient(std::shared_ptr<Channel> channel, const std::string& db)
+ : stub_(RouteGuide::NewStub(channel)) {
+ examples::ParseDb(db, &feature_list_);
+ }
+
+ void GetFeature() {
+ Point point;
+ Feature feature;
+ point = MakePoint(409146138, -746188906);
+ GetOneFeature(point, &feature);
+ point = MakePoint(0, 0);
+ GetOneFeature(point, &feature);
+ }
+
+ void ListFeatures() {
+ examples::Rectangle rect;
+ Feature feature;
+ ClientContext context;
+
+ rect.mutable_lo()->set_latitude(400000000);
+ rect.mutable_lo()->set_longitude(-750000000);
+ rect.mutable_hi()->set_latitude(420000000);
+ rect.mutable_hi()->set_longitude(-730000000);
+ std::cout << "Looking for features between 40, -75 and 42, -73"
+ << std::endl;
+
+ std::unique_ptr<ClientReader<Feature> > reader(
+ stub_->ListFeatures(&context, rect));
+ while (reader->Read(&feature)) {
+ std::cout << "Found feature called "
+ << feature.name() << " at "
+ << feature.location().latitude()/kCoordFactor_ << ", "
+ << feature.location().longitude()/kCoordFactor_ << std::endl;
+ }
+ Status status = reader->Finish();
+ if (status.ok()) {
+ std::cout << "ListFeatures rpc succeeded." << std::endl;
+ } else {
+ std::cout << "ListFeatures rpc failed." << std::endl;
+ }
+ }
+
+ void RecordRoute() {
+ Point point;
+ RouteSummary stats;
+ ClientContext context;
+ const int kPoints = 10;
+ unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
+
+ std::default_random_engine generator(seed);
+ std::uniform_int_distribution<int> feature_distribution(
+ 0, feature_list_.size() - 1);
+ std::uniform_int_distribution<int> delay_distribution(
+ 500, 1500);
+
+ std::unique_ptr<ClientWriter<Point> > writer(
+ stub_->RecordRoute(&context, &stats));
+ for (int i = 0; i < kPoints; i++) {
+ const Feature& f = feature_list_[feature_distribution(generator)];
+ std::cout << "Visiting point "
+ << f.location().latitude()/kCoordFactor_ << ", "
+ << f.location().longitude()/kCoordFactor_ << std::endl;
+ if (!writer->Write(f.location())) {
+ // Broken stream.
+ break;
+ }
+ std::this_thread::sleep_for(std::chrono::milliseconds(
+ delay_distribution(generator)));
+ }
+ writer->WritesDone();
+ Status status = writer->Finish();
+ if (status.ok()) {
+ std::cout << "Finished trip with " << stats.point_count() << " points\n"
+ << "Passed " << stats.feature_count() << " features\n"
+ << "Travelled " << stats.distance() << " meters\n"
+ << "It took " << stats.elapsed_time() << " seconds"
+ << std::endl;
+ } else {
+ std::cout << "RecordRoute rpc failed." << std::endl;
+ }
+ }
+
+ void RouteChat() {
+ ClientContext context;
+
+ std::shared_ptr<ClientReaderWriter<RouteNote, RouteNote> > stream(
+ stub_->RouteChat(&context));
+
+ std::thread writer([stream]() {
+ std::vector<RouteNote> notes{
+ MakeRouteNote("First message", 0, 0),
+ MakeRouteNote("Second message", 0, 1),
+ MakeRouteNote("Third message", 1, 0),
+ MakeRouteNote("Fourth message", 0, 0)};
+ for (const RouteNote& note : notes) {
+ std::cout << "Sending message " << note.message()
+ << " at " << note.location().latitude() << ", "
+ << note.location().longitude() << std::endl;
+ stream->Write(note);
+ }
+ stream->WritesDone();
+ });
+
+ RouteNote server_note;
+ while (stream->Read(&server_note)) {
+ std::cout << "Got message " << server_note.message()
+ << " at " << server_note.location().latitude() << ", "
+ << server_note.location().longitude() << std::endl;
+ }
+ writer.join();
+ Status status = stream->Finish();
+ if (!status.ok()) {
+ std::cout << "RouteChat rpc failed." << std::endl;
+ }
+ }
+
+ private:
+
+ bool GetOneFeature(const Point& point, Feature* feature) {
+ ClientContext context;
+ Status status = stub_->GetFeature(&context, point, feature);
+ if (!status.ok()) {
+ std::cout << "GetFeature rpc failed." << std::endl;
+ return false;
+ }
+ if (!feature->has_location()) {
+ std::cout << "Server returns incomplete feature." << std::endl;
+ return false;
+ }
+ if (feature->name().empty()) {
+ std::cout << "Found no feature at "
+ << feature->location().latitude()/kCoordFactor_ << ", "
+ << feature->location().longitude()/kCoordFactor_ << std::endl;
+ } else {
+ std::cout << "Found feature called " << feature->name() << " at "
+ << feature->location().latitude()/kCoordFactor_ << ", "
+ << feature->location().longitude()/kCoordFactor_ << std::endl;
+ }
+ return true;
+ }
+
+ const float kCoordFactor_ = 10000000.0;
+ std::unique_ptr<RouteGuide::Stub> stub_;
+ std::vector<Feature> feature_list_;
+};
+
+int main(int argc, char** argv) {
+ // Expect only arg: --db_path=path/to/route_guide_db.json.
+ std::string db = examples::GetDbFileContent(argc, argv);
+ RouteGuideClient guide(
+ grpc::CreateChannel("localhost:50051", grpc::InsecureCredentials(),
+ ChannelArguments()),
+ db);
+
+ std::cout << "-------------- GetFeature --------------" << std::endl;
+ guide.GetFeature();
+ std::cout << "-------------- ListFeatures --------------" << std::endl;
+ guide.ListFeatures();
+ std::cout << "-------------- RecordRoute --------------" << std::endl;
+ guide.RecordRoute();
+ std::cout << "-------------- RouteChat --------------" << std::endl;
+ guide.RouteChat();
+
+ return 0;
+}
diff --git a/examples/cpp/route_guide/route_guide_db.json b/examples/cpp/route_guide/route_guide_db.json
new file mode 100644
index 0000000000..9d6a980ab7
--- /dev/null
+++ b/examples/cpp/route_guide/route_guide_db.json
@@ -0,0 +1,601 @@
+[{
+ "location": {
+ "latitude": 407838351,
+ "longitude": -746143763
+ },
+ "name": "Patriots Path, Mendham, NJ 07945, USA"
+}, {
+ "location": {
+ "latitude": 408122808,
+ "longitude": -743999179
+ },
+ "name": "101 New Jersey 10, Whippany, NJ 07981, USA"
+}, {
+ "location": {
+ "latitude": 413628156,
+ "longitude": -749015468
+ },
+ "name": "U.S. 6, Shohola, PA 18458, USA"
+}, {
+ "location": {
+ "latitude": 419999544,
+ "longitude": -740371136
+ },
+ "name": "5 Conners Road, Kingston, NY 12401, USA"
+}, {
+ "location": {
+ "latitude": 414008389,
+ "longitude": -743951297
+ },
+ "name": "Mid Hudson Psychiatric Center, New Hampton, NY 10958, USA"
+}, {
+ "location": {
+ "latitude": 419611318,
+ "longitude": -746524769
+ },
+ "name": "287 Flugertown Road, Livingston Manor, NY 12758, USA"
+}, {
+ "location": {
+ "latitude": 406109563,
+ "longitude": -742186778
+ },
+ "name": "4001 Tremley Point Road, Linden, NJ 07036, USA"
+}, {
+ "location": {
+ "latitude": 416802456,
+ "longitude": -742370183
+ },
+ "name": "352 South Mountain Road, Wallkill, NY 12589, USA"
+}, {
+ "location": {
+ "latitude": 412950425,
+ "longitude": -741077389
+ },
+ "name": "Bailey Turn Road, Harriman, NY 10926, USA"
+}, {
+ "location": {
+ "latitude": 412144655,
+ "longitude": -743949739
+ },
+ "name": "193-199 Wawayanda Road, Hewitt, NJ 07421, USA"
+}, {
+ "location": {
+ "latitude": 415736605,
+ "longitude": -742847522
+ },
+ "name": "406-496 Ward Avenue, Pine Bush, NY 12566, USA"
+}, {
+ "location": {
+ "latitude": 413843930,
+ "longitude": -740501726
+ },
+ "name": "162 Merrill Road, Highland Mills, NY 10930, USA"
+}, {
+ "location": {
+ "latitude": 410873075,
+ "longitude": -744459023
+ },
+ "name": "Clinton Road, West Milford, NJ 07480, USA"
+}, {
+ "location": {
+ "latitude": 412346009,
+ "longitude": -744026814
+ },
+ "name": "16 Old Brook Lane, Warwick, NY 10990, USA"
+}, {
+ "location": {
+ "latitude": 402948455,
+ "longitude": -747903913
+ },
+ "name": "3 Drake Lane, Pennington, NJ 08534, USA"
+}, {
+ "location": {
+ "latitude": 406337092,
+ "longitude": -740122226
+ },
+ "name": "6324 8th Avenue, Brooklyn, NY 11220, USA"
+}, {
+ "location": {
+ "latitude": 406421967,
+ "longitude": -747727624
+ },
+ "name": "1 Merck Access Road, Whitehouse Station, NJ 08889, USA"
+}, {
+ "location": {
+ "latitude": 416318082,
+ "longitude": -749677716
+ },
+ "name": "78-98 Schalck Road, Narrowsburg, NY 12764, USA"
+}, {
+ "location": {
+ "latitude": 415301720,
+ "longitude": -748416257
+ },
+ "name": "282 Lakeview Drive Road, Highland Lake, NY 12743, USA"
+}, {
+ "location": {
+ "latitude": 402647019,
+ "longitude": -747071791
+ },
+ "name": "330 Evelyn Avenue, Hamilton Township, NJ 08619, USA"
+}, {
+ "location": {
+ "latitude": 412567807,
+ "longitude": -741058078
+ },
+ "name": "New York State Reference Route 987E, Southfields, NY 10975, USA"
+}, {
+ "location": {
+ "latitude": 416855156,
+ "longitude": -744420597
+ },
+ "name": "103-271 Tempaloni Road, Ellenville, NY 12428, USA"
+}, {
+ "location": {
+ "latitude": 404663628,
+ "longitude": -744820157
+ },
+ "name": "1300 Airport Road, North Brunswick Township, NJ 08902, USA"
+}, {
+ "location": {
+ "latitude": 407113723,
+ "longitude": -749746483
+ },
+ "name": ""
+}, {
+ "location": {
+ "latitude": 402133926,
+ "longitude": -743613249
+ },
+ "name": ""
+}, {
+ "location": {
+ "latitude": 400273442,
+ "longitude": -741220915
+ },
+ "name": ""
+}, {
+ "location": {
+ "latitude": 411236786,
+ "longitude": -744070769
+ },
+ "name": ""
+}, {
+ "location": {
+ "latitude": 411633782,
+ "longitude": -746784970
+ },
+ "name": "211-225 Plains Road, Augusta, NJ 07822, USA"
+}, {
+ "location": {
+ "latitude": 415830701,
+ "longitude": -742952812
+ },
+ "name": ""
+}, {
+ "location": {
+ "latitude": 413447164,
+ "longitude": -748712898
+ },
+ "name": "165 Pedersen Ridge Road, Milford, PA 18337, USA"
+}, {
+ "location": {
+ "latitude": 405047245,
+ "longitude": -749800722
+ },
+ "name": "100-122 Locktown Road, Frenchtown, NJ 08825, USA"
+}, {
+ "location": {
+ "latitude": 418858923,
+ "longitude": -746156790
+ },
+ "name": ""
+}, {
+ "location": {
+ "latitude": 417951888,
+ "longitude": -748484944
+ },
+ "name": "650-652 Willi Hill Road, Swan Lake, NY 12783, USA"
+}, {
+ "location": {
+ "latitude": 407033786,
+ "longitude": -743977337
+ },
+ "name": "26 East 3rd Street, New Providence, NJ 07974, USA"
+}, {
+ "location": {
+ "latitude": 417548014,
+ "longitude": -740075041
+ },
+ "name": ""
+}, {
+ "location": {
+ "latitude": 410395868,
+ "longitude": -744972325
+ },
+ "name": ""
+}, {
+ "location": {
+ "latitude": 404615353,
+ "longitude": -745129803
+ },
+ "name": ""
+}, {
+ "location": {
+ "latitude": 406589790,
+ "longitude": -743560121
+ },
+ "name": "611 Lawrence Avenue, Westfield, NJ 07090, USA"
+}, {
+ "location": {
+ "latitude": 414653148,
+ "longitude": -740477477
+ },
+ "name": "18 Lannis Avenue, New Windsor, NY 12553, USA"
+}, {
+ "location": {
+ "latitude": 405957808,
+ "longitude": -743255336
+ },
+ "name": "82-104 Amherst Avenue, Colonia, NJ 07067, USA"
+}, {
+ "location": {
+ "latitude": 411733589,
+ "longitude": -741648093
+ },
+ "name": "170 Seven Lakes Drive, Sloatsburg, NY 10974, USA"
+}, {
+ "location": {
+ "latitude": 412676291,
+ "longitude": -742606606
+ },
+ "name": "1270 Lakes Road, Monroe, NY 10950, USA"
+}, {
+ "location": {
+ "latitude": 409224445,
+ "longitude": -748286738
+ },
+ "name": "509-535 Alphano Road, Great Meadows, NJ 07838, USA"
+}, {
+ "location": {
+ "latitude": 406523420,
+ "longitude": -742135517
+ },
+ "name": "652 Garden Street, Elizabeth, NJ 07202, USA"
+}, {
+ "location": {
+ "latitude": 401827388,
+ "longitude": -740294537
+ },
+ "name": "349 Sea Spray Court, Neptune City, NJ 07753, USA"
+}, {
+ "location": {
+ "latitude": 410564152,
+ "longitude": -743685054
+ },
+ "name": "13-17 Stanley Street, West Milford, NJ 07480, USA"
+}, {
+ "location": {
+ "latitude": 408472324,
+ "longitude": -740726046
+ },
+ "name": "47 Industrial Avenue, Teterboro, NJ 07608, USA"
+}, {
+ "location": {
+ "latitude": 412452168,
+ "longitude": -740214052
+ },
+ "name": "5 White Oak Lane, Stony Point, NY 10980, USA"
+}, {
+ "location": {
+ "latitude": 409146138,
+ "longitude": -746188906
+ },
+ "name": "Berkshire Valley Management Area Trail, Jefferson, NJ, USA"
+}, {
+ "location": {
+ "latitude": 404701380,
+ "longitude": -744781745
+ },
+ "name": "1007 Jersey Avenue, New Brunswick, NJ 08901, USA"
+}, {
+ "location": {
+ "latitude": 409642566,
+ "longitude": -746017679
+ },
+ "name": "6 East Emerald Isle Drive, Lake Hopatcong, NJ 07849, USA"
+}, {
+ "location": {
+ "latitude": 408031728,
+ "longitude": -748645385
+ },
+ "name": "1358-1474 New Jersey 57, Port Murray, NJ 07865, USA"
+}, {
+ "location": {
+ "latitude": 413700272,
+ "longitude": -742135189
+ },
+ "name": "367 Prospect Road, Chester, NY 10918, USA"
+}, {
+ "location": {
+ "latitude": 404310607,
+ "longitude": -740282632
+ },
+ "name": "10 Simon Lake Drive, Atlantic Highlands, NJ 07716, USA"
+}, {
+ "location": {
+ "latitude": 409319800,
+ "longitude": -746201391
+ },
+ "name": "11 Ward Street, Mount Arlington, NJ 07856, USA"
+}, {
+ "location": {
+ "latitude": 406685311,
+ "longitude": -742108603
+ },
+ "name": "300-398 Jefferson Avenue, Elizabeth, NJ 07201, USA"
+}, {
+ "location": {
+ "latitude": 419018117,
+ "longitude": -749142781
+ },
+ "name": "43 Dreher Road, Roscoe, NY 12776, USA"
+}, {
+ "location": {
+ "latitude": 412856162,
+ "longitude": -745148837
+ },
+ "name": "Swan Street, Pine Island, NY 10969, USA"
+}, {
+ "location": {
+ "latitude": 416560744,
+ "longitude": -746721964
+ },
+ "name": "66 Pleasantview Avenue, Monticello, NY 12701, USA"
+}, {
+ "location": {
+ "latitude": 405314270,
+ "longitude": -749836354
+ },
+ "name": ""
+}, {
+ "location": {
+ "latitude": 414219548,
+ "longitude": -743327440
+ },
+ "name": ""
+}, {
+ "location": {
+ "latitude": 415534177,
+ "longitude": -742900616
+ },
+ "name": "565 Winding Hills Road, Montgomery, NY 12549, USA"
+}, {
+ "location": {
+ "latitude": 406898530,
+ "longitude": -749127080
+ },
+ "name": "231 Rocky Run Road, Glen Gardner, NJ 08826, USA"
+}, {
+ "location": {
+ "latitude": 407586880,
+ "longitude": -741670168
+ },
+ "name": "100 Mount Pleasant Avenue, Newark, NJ 07104, USA"
+}, {
+ "location": {
+ "latitude": 400106455,
+ "longitude": -742870190
+ },
+ "name": "517-521 Huntington Drive, Manchester Township, NJ 08759, USA"
+}, {
+ "location": {
+ "latitude": 400066188,
+ "longitude": -746793294
+ },
+ "name": ""
+}, {
+ "location": {
+ "latitude": 418803880,
+ "longitude": -744102673
+ },
+ "name": "40 Mountain Road, Napanoch, NY 12458, USA"
+}, {
+ "location": {
+ "latitude": 414204288,
+ "longitude": -747895140
+ },
+ "name": ""
+}, {
+ "location": {
+ "latitude": 414777405,
+ "longitude": -740615601
+ },
+ "name": ""
+}, {
+ "location": {
+ "latitude": 415464475,
+ "longitude": -747175374
+ },
+ "name": "48 North Road, Forestburgh, NY 12777, USA"
+}, {
+ "location": {
+ "latitude": 404062378,
+ "longitude": -746376177
+ },
+ "name": ""
+}, {
+ "location": {
+ "latitude": 405688272,
+ "longitude": -749285130
+ },
+ "name": ""
+}, {
+ "location": {
+ "latitude": 400342070,
+ "longitude": -748788996
+ },
+ "name": ""
+}, {
+ "location": {
+ "latitude": 401809022,
+ "longitude": -744157964
+ },
+ "name": ""
+}, {
+ "location": {
+ "latitude": 404226644,
+ "longitude": -740517141
+ },
+ "name": "9 Thompson Avenue, Leonardo, NJ 07737, USA"
+}, {
+ "location": {
+ "latitude": 410322033,
+ "longitude": -747871659
+ },
+ "name": ""
+}, {
+ "location": {
+ "latitude": 407100674,
+ "longitude": -747742727
+ },
+ "name": ""
+}, {
+ "location": {
+ "latitude": 418811433,
+ "longitude": -741718005
+ },
+ "name": "213 Bush Road, Stone Ridge, NY 12484, USA"
+}, {
+ "location": {
+ "latitude": 415034302,
+ "longitude": -743850945
+ },
+ "name": ""
+}, {
+ "location": {
+ "latitude": 411349992,
+ "longitude": -743694161
+ },
+ "name": ""
+}, {
+ "location": {
+ "latitude": 404839914,
+ "longitude": -744759616
+ },
+ "name": "1-17 Bergen Court, New Brunswick, NJ 08901, USA"
+}, {
+ "location": {
+ "latitude": 414638017,
+ "longitude": -745957854
+ },
+ "name": "35 Oakland Valley Road, Cuddebackville, NY 12729, USA"
+}, {
+ "location": {
+ "latitude": 412127800,
+ "longitude": -740173578
+ },
+ "name": ""
+}, {
+ "location": {
+ "latitude": 401263460,
+ "longitude": -747964303
+ },
+ "name": ""
+}, {
+ "location": {
+ "latitude": 412843391,
+ "longitude": -749086026
+ },
+ "name": ""
+}, {
+ "location": {
+ "latitude": 418512773,
+ "longitude": -743067823
+ },
+ "name": ""
+}, {
+ "location": {
+ "latitude": 404318328,
+ "longitude": -740835638
+ },
+ "name": "42-102 Main Street, Belford, NJ 07718, USA"
+}, {
+ "location": {
+ "latitude": 419020746,
+ "longitude": -741172328
+ },
+ "name": ""
+}, {
+ "location": {
+ "latitude": 404080723,
+ "longitude": -746119569
+ },
+ "name": ""
+}, {
+ "location": {
+ "latitude": 401012643,
+ "longitude": -744035134
+ },
+ "name": ""
+}, {
+ "location": {
+ "latitude": 404306372,
+ "longitude": -741079661
+ },
+ "name": ""
+}, {
+ "location": {
+ "latitude": 403966326,
+ "longitude": -748519297
+ },
+ "name": ""
+}, {
+ "location": {
+ "latitude": 405002031,
+ "longitude": -748407866
+ },
+ "name": ""
+}, {
+ "location": {
+ "latitude": 409532885,
+ "longitude": -742200683
+ },
+ "name": ""
+}, {
+ "location": {
+ "latitude": 416851321,
+ "longitude": -742674555
+ },
+ "name": ""
+}, {
+ "location": {
+ "latitude": 406411633,
+ "longitude": -741722051
+ },
+ "name": "3387 Richmond Terrace, Staten Island, NY 10303, USA"
+}, {
+ "location": {
+ "latitude": 413069058,
+ "longitude": -744597778
+ },
+ "name": "261 Van Sickle Road, Goshen, NY 10924, USA"
+}, {
+ "location": {
+ "latitude": 418465462,
+ "longitude": -746859398
+ },
+ "name": ""
+}, {
+ "location": {
+ "latitude": 411733222,
+ "longitude": -744228360
+ },
+ "name": ""
+}, {
+ "location": {
+ "latitude": 410248224,
+ "longitude": -747127767
+ },
+ "name": "3 Hasta Way, Newton, NJ 07860, USA"
+}]
diff --git a/examples/cpp/route_guide/route_guide_server.cc b/examples/cpp/route_guide/route_guide_server.cc
new file mode 100644
index 0000000000..b37539299a
--- /dev/null
+++ b/examples/cpp/route_guide/route_guide_server.cc
@@ -0,0 +1,202 @@
+/*
+ *
+ * Copyright 2015, Google Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include <algorithm>
+#include <chrono>
+#include <cmath>
+#include <iostream>
+#include <memory>
+#include <string>
+
+#include <grpc/grpc.h>
+#include <grpc++/server.h>
+#include <grpc++/server_builder.h>
+#include <grpc++/server_context.h>
+#include <grpc++/server_credentials.h>
+#include "helper.h"
+#include "route_guide.grpc.pb.h"
+
+using grpc::Server;
+using grpc::ServerBuilder;
+using grpc::ServerContext;
+using grpc::ServerReader;
+using grpc::ServerReaderWriter;
+using grpc::ServerWriter;
+using grpc::Status;
+using examples::Point;
+using examples::Feature;
+using examples::Rectangle;
+using examples::RouteSummary;
+using examples::RouteNote;
+using examples::RouteGuide;
+using std::chrono::system_clock;
+
+
+float ConvertToRadians(float num) {
+ return num * 3.1415926 /180;
+}
+
+float GetDistance(const Point& start, const Point& end) {
+ const float kCoordFactor = 10000000.0;
+ float lat_1 = start.latitude() / kCoordFactor;
+ float lat_2 = end.latitude() / kCoordFactor;
+ float lon_1 = start.longitude() / kCoordFactor;
+ float lon_2 = end.longitude() / kCoordFactor;
+ float lat_rad_1 = ConvertToRadians(lat_1);
+ float lat_rad_2 = ConvertToRadians(lat_2);
+ float delta_lat_rad = ConvertToRadians(lat_2-lat_1);
+ float delta_lon_rad = ConvertToRadians(lon_2-lon_1);
+
+ float a = pow(sin(delta_lat_rad/2), 2) + cos(lat_rad_1) * cos(lat_rad_2) *
+ pow(sin(delta_lon_rad/2), 2);
+ float c = 2 * atan2(sqrt(a), sqrt(1-a));
+ int R = 6371000; // metres
+
+ return R * c;
+}
+
+std::string GetFeatureName(const Point& point,
+ const std::vector<Feature>& feature_list) {
+ for (const Feature& f : feature_list) {
+ if (f.location().latitude() == point.latitude() &&
+ f.location().longitude() == point.longitude()) {
+ return f.name();
+ }
+ }
+ return "";
+}
+
+class RouteGuideImpl final : public RouteGuide::Service {
+ public:
+ explicit RouteGuideImpl(const std::string& db) {
+ examples::ParseDb(db, &feature_list_);
+ }
+
+ 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;
+ }
+
+ Status ListFeatures(ServerContext* context,
+ const examples::Rectangle* rectangle,
+ ServerWriter<Feature>* writer) override {
+ auto lo = rectangle->lo();
+ auto hi = rectangle->hi();
+ long left = (std::min)(lo.longitude(), hi.longitude());
+ long right = (std::max)(lo.longitude(), hi.longitude());
+ long top = (std::max)(lo.latitude(), hi.latitude());
+ long bottom = (std::min)(lo.latitude(), hi.latitude());
+ for (const Feature& f : feature_list_) {
+ if (f.location().longitude() >= left &&
+ f.location().longitude() <= right &&
+ f.location().latitude() >= bottom &&
+ f.location().latitude() <= top) {
+ writer->Write(f);
+ }
+ }
+ return Status::OK;
+ }
+
+ Status RecordRoute(ServerContext* context, ServerReader<Point>* reader,
+ RouteSummary* summary) override {
+ Point point;
+ int point_count = 0;
+ int feature_count = 0;
+ float distance = 0.0;
+ Point previous;
+
+ system_clock::time_point start_time = system_clock::now();
+ while (reader->Read(&point)) {
+ point_count++;
+ if (!GetFeatureName(point, feature_list_).empty()) {
+ feature_count++;
+ }
+ if (point_count != 1) {
+ distance += GetDistance(previous, point);
+ }
+ previous = point;
+ }
+ system_clock::time_point end_time = system_clock::now();
+ summary->set_point_count(point_count);
+ summary->set_feature_count(feature_count);
+ summary->set_distance(static_cast<long>(distance));
+ auto secs = std::chrono::duration_cast<std::chrono::seconds>(
+ end_time - start_time);
+ summary->set_elapsed_time(secs.count());
+
+ return Status::OK;
+ }
+
+ Status RouteChat(ServerContext* context,
+ ServerReaderWriter<RouteNote, RouteNote>* stream) override {
+ std::vector<RouteNote> received_notes;
+ RouteNote note;
+ while (stream->Read(&note)) {
+ for (const RouteNote& n : received_notes) {
+ if (n.location().latitude() == note.location().latitude() &&
+ n.location().longitude() == note.location().longitude()) {
+ stream->Write(n);
+ }
+ }
+ received_notes.push_back(note);
+ }
+
+ return Status::OK;
+ }
+
+ private:
+
+ std::vector<Feature> feature_list_;
+};
+
+void RunServer(const std::string& db_path) {
+ std::string server_address("0.0.0.0:50051");
+ RouteGuideImpl service(db_path);
+
+ ServerBuilder builder;
+ builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
+ builder.RegisterService(&service);
+ std::unique_ptr<Server> server(builder.BuildAndStart());
+ std::cout << "Server listening on " << server_address << std::endl;
+ server->Wait();
+}
+
+int main(int argc, char** argv) {
+ // Expect only arg: --db_path=path/to/route_guide_db.json.
+ std::string db = examples::GetDbFileContent(argc, argv);
+ RunServer(db);
+
+ return 0;
+}