gRPC Basics - Android Java

This tutorial provides a basic Android Java 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 client code using the protocol buffer compiler.
  • Use the Java gRPC API to write a simple mobile client for your service.

It assumes that you have read theOverview and are familiar withprotocol buffers.This guide also does not cover anything on the server side. You can check theJava guide for more information.

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 ingrpc-java’s examples/android. To download the example, clone the grpc-java repository by running the following command:

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

Then change your current directory to grpc-java/examples/android:

  1. $ cd grpc-java/examples/android

You also should have the relevant tools installed to generate the clientinterface code - if you don’t already, follow the setup instructions in thegrpc-java README.

Defining the service

Our first step (as you’ll know from theOverview) is to define the gRPC service and the method request and response types usingprotocol buffers. You can see the complete .proto file inrouteguide/app/src/main/proto/route_guide.proto.

As we’re generating Java code in this example, we’ve specified a java_package file option in our .proto:

  1. option java_package = "io.grpc.examples";

This specifies the package we want to use for our generated Java classes. If no explicit java_package option is given in the .proto file, then by default the proto package (specified using the “package” keyword) will be used. However, proto packages generally do not make good Java packages since proto packages are not expected to start with reverse domain names. If we generate code in another language from this .proto, the java_package option has no effect.

To define a service, we specify a named service in the .proto file:

  1. service RouteGuide {
  2. ...
  3. }

Then we define rpc methods inside our 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 stuband waits for a response to come back, just like a normal function call.
  1. // Obtains the feature at a given position.
  2. rpc GetFeature(Point) returns (Feature) {}
  • A server-side streaming RPC where the client sends a request to the serverand gets a stream to read a sequence of messages back. The client reads fromthe returned stream until there are no more messages. As you can see in ourexample, you specify a server-side streaming method by placing the streamkeyword before the response type.
  1. // Obtains the Features available within the given Rectangle. Results are
  2. // streamed rather than returned at once (e.g. in a response message with a
  3. // repeated field), as the rectangle may cover a large area and contain a
  4. // huge number of features.
  5. rpc ListFeatures(Rectangle) returns (stream Feature) {}
  • A client-side streaming RPC where the client writes a sequence of messagesand sends them to the server, again using a provided stream. Once the clienthas finished writing the messages, it waits for the server to read them alland return its response. You specify a client-side streaming method by placingthe stream keyword before the request type.
  1. // Accepts a stream of Points on a route being traversed, returning a
  2. // RouteSummary when traversal is completed.
  3. rpc RecordRoute(stream Point) returns (RouteSummary) {}
  • A bidirectional streaming RPC where both sides send a sequence of messagesusing a read-write stream. The two streams operate independently, so clientsand servers can read and write in whatever order they like: for example, theserver could wait to receive all the client messages before writing itsresponses, or it could alternately read a message then write a message, orsome other combination of reads and writes. The order of messages in eachstream is preserved. You specify this type of method by placing the streamkeyword before both the request and the response.
  1. // Accepts a stream of RouteNotes sent while a route is being traversed,
  2. // while receiving other RouteNotes (e.g. from other users).
  3. rpc RouteChat(stream RouteNote) returns (stream RouteNote) {}

Our .proto file also contains protocol buffer message type definitions for allthe request and response types used in our service methods - for example, here’sthe Point message type:

  1. // Points are represented as latitude-longitude pairs in the E7 representation
  2. // (degrees multiplied by 10**7 and rounded to the nearest integer).
  3. // Latitudes should be in the range +/- 90 degrees and longitude should be in
  4. // the range +/- 180 degrees (inclusive).
  5. message Point {
  6. int32 latitude = 1;
  7. int32 longitude = 2;
  8. }

Generating client code

Next we need to generate the gRPC client interfaces from our .protoservice definition. We do this using the protocol buffer compiler protoc witha special gRPC Java plugin. You need to use theproto3 compiler (which supportsboth proto2 and proto3 syntax) in order to generate gRPC services.

The build system for this example is also part of the Java-gRPC build. Refer tothegrpc-java README andbuild.gradle for how to generate code from yourown .proto files. Note that for Android, we will use protobuf lite which isoptimized for mobile usecase.

The following classes are generated from our service definition:

  • Feature.java, Point.java, Rectangle.java, and others which containall the protocol buffer code to populate, serialize, and retrieve our requestand response message types.
  • RouteGuideGrpc.java which contains (along with some other useful code):
    • a base class for RouteGuide servers to implement,RouteGuideGrpc.RouteGuideImplBase, with all the methods defined in the RouteGuideservice.
    • stub classes that clients can use to talk to a RouteGuide server.

Creating the client

In this section, we’ll look at creating a Java client for our RouteGuide service. You can see our complete example client code inrouteguide/app/src/main/java/io/grpc/routeguideexample/RouteGuideActivity.java.

Creating a stub

To call service methods, we first need to create a stub, or rather, two stubs:

  • a blocking/synchronous stub: this means that the RPC call waits for the server to respond, and will either return a response or raise an exception.
  • a non-blocking/asynchronous stub that makes non-blocking calls to the server, where the response is returned asynchronously. You can make certain types of streaming call only using the asynchronous stub.

First we need to create a gRPC channel for our stub, specifying the server address and port we want to connect to:We use a ManagedChannelBuilder to create the channel.

  1. mChannel = ManagedChannelBuilder.forAddress(host, port).usePlaintext(true).build();

Now we can use the channel to create our stubs using the newStub and newBlockingStub methods provided in the RouteGuideGrpc class we generated from our .proto.

  1. blockingStub = RouteGuideGrpc.newBlockingStub(mChannel);
  2. asyncStub = RouteGuideGrpc.newStub(mChannel);

Calling service methods

Now let’s look at how we call our service methods.

Simple RPC

Calling the simple RPC GetFeature on the blocking stub is as straightforward as calling a local method.

  1. Point request = Point.newBuilder().setLatitude(lat).setLongitude(lon).build();
  2. Feature feature = blockingStub.getFeature(request);

We create and populate a request protocol buffer object (in our case Point), pass it to the getFeature() method on our blocking stub, and get back a Feature.

Server-side streaming RPC

Next, let’s look at a server-side streaming call to ListFeatures, which returns a stream of geographical Features:

  1. Rectangle request =
  2. Rectangle.newBuilder()
  3. .setLo(Point.newBuilder().setLatitude(lowLat).setLongitude(lowLon).build())
  4. .setHi(Point.newBuilder().setLatitude(hiLat).setLongitude(hiLon).build()).build();
  5. Iterator<Feature> features = blockingStub.listFeatures(request);

As you can see, it’s very similar to the simple RPC we just looked at, except instead of returning a single Feature, the method returns an Iterator that the client can use to read all the returned Features.

Client-side streaming RPC

Now for something a little more complicated: the client-side streaming method RecordRoute, where we send a stream of Points to the server and get back a single RouteSummary. For this method we need to use the asynchronous stub. If you’ve already readCreating the server some of this may look very familiar - asynchronous streaming RPCs are implemented in a similar way on both sides.

  1. private String recordRoute(List<Point> points, int numPoints, RouteGuideStub asyncStub)
  2. throws InterruptedException, RuntimeException {
  3. final StringBuffer logs = new StringBuffer();
  4. appendLogs(logs, "*** RecordRoute");
  5. final CountDownLatch finishLatch = new CountDownLatch(1);
  6. StreamObserver<RouteSummary> responseObserver = new StreamObserver<RouteSummary>() {
  7. @Override
  8. public void onNext(RouteSummary summary) {
  9. appendLogs(logs, "Finished trip with {0} points. Passed {1} features. "
  10. + "Travelled {2} meters. It took {3} seconds.", summary.getPointCount(),
  11. summary.getFeatureCount(), summary.getDistance(),
  12. summary.getElapsedTime());
  13. }
  14. @Override
  15. public void onError(Throwable t) {
  16. failed = t;
  17. finishLatch.countDown();
  18. }
  19. @Override
  20. public void onCompleted() {
  21. appendLogs(logs, "Finished RecordRoute");
  22. finishLatch.countDown();
  23. }
  24. };
  25. StreamObserver<Point> requestObserver = asyncStub.recordRoute(responseObserver);
  26. try {
  27. // Send numPoints points randomly selected from the points list.
  28. Random rand = new Random();
  29. for (int i = 0; i < numPoints; ++i) {
  30. int index = rand.nextInt(points.size());
  31. Point point = points.get(index);
  32. appendLogs(logs, "Visiting point {0}, {1}", RouteGuideUtil.getLatitude(point),
  33. RouteGuideUtil.getLongitude(point));
  34. requestObserver.onNext(point);
  35. // Sleep for a bit before sending the next one.
  36. Thread.sleep(rand.nextInt(1000) + 500);
  37. if (finishLatch.getCount() == 0) {
  38. // RPC completed or errored before we finished sending.
  39. // Sending further requests won't error, but they will just be thrown away.
  40. break;
  41. }
  42. }
  43. } catch (RuntimeException e) {
  44. // Cancel RPC
  45. requestObserver.onError(e);
  46. throw e;
  47. }
  48. // Mark the end of requests
  49. requestObserver.onCompleted();
  50. // Receiving happens asynchronously
  51. if (!finishLatch.await(1, TimeUnit.MINUTES)) {
  52. throw new RuntimeException(
  53. "Could not finish rpc within 1 minute, the server is likely down");
  54. }
  55. if (failed != null) {
  56. throw new RuntimeException(failed);
  57. }
  58. return logs.toString();
  59. }

As you can see, to call this method we need to create a StreamObserver, which implements a special interface for the server to call with its RouteSummary response. In our StreamObserver we:

  • Override the onNext() method to print out the returned information when the server writes a RouteSummary to the message stream.
  • Override the onCompleted() method (called when the server has completed the call on its side) to set a SettableFuture that we can check to see if the server has finished writing.

We then pass the StreamObserver to the asynchronous stub’s recordRoute() method and get back our own StreamObserver request observer to write our Points to send to the server. Once we’ve finished writing points, we use the request observer’s onCompleted() method to tell gRPC that we’ve finished writing on the client side. Once we’re done, we check our SettableFuture to check that the server has completed on its side.

Bidirectional streaming RPC

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

  1. private String routeChat(RouteGuideStub asyncStub) throws InterruptedException,
  2. RuntimeException {
  3. final StringBuffer logs = new StringBuffer();
  4. appendLogs(logs, "*** RouteChat");
  5. final CountDownLatch finishLatch = new CountDownLatch(1);
  6. StreamObserver<RouteNote> requestObserver =
  7. asyncStub.routeChat(new StreamObserver<RouteNote>() {
  8. @Override
  9. public void onNext(RouteNote note) {
  10. appendLogs(logs, "Got message \"{0}\" at {1}, {2}", note.getMessage(),
  11. note.getLocation().getLatitude(),
  12. note.getLocation().getLongitude());
  13. }
  14. @Override
  15. public void onError(Throwable t) {
  16. failed = t;
  17. finishLatch.countDown();
  18. }
  19. @Override
  20. public void onCompleted() {
  21. appendLogs(logs,"Finished RouteChat");
  22. finishLatch.countDown();
  23. }
  24. });
  25. try {
  26. RouteNote[] requests =
  27. {newNote("First message", 0, 0), newNote("Second message", 0, 1),
  28. newNote("Third message", 1, 0), newNote("Fourth message", 1, 1)};
  29. for (RouteNote request : requests) {
  30. appendLogs(logs, "Sending message \"{0}\" at {1}, {2}", request.getMessage(),
  31. request.getLocation().getLatitude(),
  32. request.getLocation().getLongitude());
  33. requestObserver.onNext(request);
  34. }
  35. } catch (RuntimeException e) {
  36. // Cancel RPC
  37. requestObserver.onError(e);
  38. throw e;
  39. }
  40. // Mark the end of requests
  41. requestObserver.onCompleted();
  42. // Receiving happens asynchronously
  43. if (!finishLatch.await(1, TimeUnit.MINUTES)) {
  44. throw new RuntimeException(
  45. "Could not finish rpc within 1 minute, the server is likely down");
  46. }
  47. if (failed != null) {
  48. throw new RuntimeException(failed);
  49. }
  50. return logs.toString();
  51. }

As with our client-side streaming example, we both get and return a StreamObserver response observer, except this time we send values via our method’s response observer while the server is still writing messages to their message stream. The syntax for reading and writing here is exactly the same as for our client-streaming method. 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!

Follow the instructions in theexample directory README to build and run theclient and server.