gRPC Basics - Dart

This tutorial provides a basic Dart programmer’s introduction toworking 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 Dart gRPC API to write a simple client and server for your service.

It assumes that you have read theOverview and are familiarwithprotocol buffers. Note that theexample in this tutorial uses the proto3 version of the protocol bufferslanguage: you can find out more in theproto3 languageguide.

Why use gRPC?

Our example is a simple route mapping application that lets clients getinformation about features on their route, create a summary of their route, andexchange route information such as traffic updates with the server and otherclients.

With gRPC we can define our service once in a .proto file and implement clientsand servers in any of gRPC’s supported languages, which in turn can be run inenvironments ranging from servers inside Google to your own tablet - all thecomplexity of communication between different languages and environments ishandled for you by gRPC. We also get all the advantages of working with protocolbuffers, including efficient serialization, a simple IDL, and easy interfaceupdating.

Example code and setup

The example code for our tutorial is ingrpc/grpc-dart/example/route_guide.To download the example, clone the grpc-dart repository by running the followingcommand:

  1. $ git clone https://github.com/grpc/grpc-dart.git

Then change your current directory to grpc-dart/example/route_guide:

  1. $ cd grpc-dart/example/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 inthe Dart quick start guide.

Defining the service

Our first step (as you’ll know from theOverview) is todefine the gRPC service and the method request and response types usingprotocol buffers. You can see thecomplete .proto file inexample/route_guide/protos/route_guide.proto.

To define a service, you specify a named service in your .proto file:

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

Then you define rpc methods inside your service definition, specifying theirrequest 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 and server code

Next we need to generate the gRPC client and server interfaces from our .protoservice definition. We do this using the protocol buffer compiler protoc witha special Dart plugin.This is similar to what we did in thequickstart guide

From the route_guide example directory run:

  1. protoc -I protos/ protos/route_guide.proto --dart_out=grpc:lib/src/generated

Running this command generates the following files in the lib/src/generateddirectory under the route_guide example directory:

  • route_guide.pb.dart
  • route_guide.pbenum.dart
  • route_guide.pbgrpc.dart
  • route_guide.pbjson.dart

This contains:

  • All the protocol buffer code to populate, serialize, and retrieve our requestand response message types
  • An interface type (or stub) for clients to call with the methods defined inthe RouteGuide service.
  • An interface type for servers to implement, also with the methods defined inthe RouteGuide service.

Creating the server

First let’s look at how we create a RouteGuide server. If you’re onlyinterested in creating gRPC clients, you can skip this section and go straighttoCreating the client (though you might find it interestinganyway!).

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 dispatch them tothe right service implementation.

You can find our example RouteGuide server ingrpc-dart/example/route_guide/lib/src/server.dart.Let’s take a closer look at how it works.

Implementing RouteGuide

As you can see, our server has a RouteGuideService class that extends thegenerated abstract RouteGuideServiceBase class:

  1. class RouteGuideService extends RouteGuideServiceBase {
  2. Future<Feature> getFeature(grpc.ServiceCall call, Point request) async {
  3. ...
  4. }
  5. Stream<Feature> listFeatures(
  6. grpc.ServiceCall call, Rectangle request) async* {
  7. ...
  8. }
  9. Future<RouteSummary> recordRoute(
  10. grpc.ServiceCall call, Stream<Point> request) async {
  11. ...
  12. }
  13. Stream<RouteNote> routeChat(
  14. grpc.ServiceCall call, Stream<RouteNote> request) async* {
  15. ...
  16. }
  17. ...
  18. }

Simple RPC

RouteGuideService implements all our service methods. Let’s look at thesimplest type first, GetFeature, which just gets a Point from the client andreturns the corresponding feature information from its database in a Feature.

  1. /// GetFeature handler. Returns a feature for the given location.
  2. /// The [context] object provides access to client metadata, cancellation, etc.
  3. @override
  4. Future<Feature> getFeature(grpc.ServiceCall call, Point request) async {
  5. return featuresDb.firstWhere((f) => f.location == request,
  6. orElse: () => Feature()..location = request);
  7. }

The method is passed a context object for the RPC and the client’s Pointprotocol buffer request. It returns a Feature protocol buffer object with theresponse information. In the method we populate the Feature with the appropriateinformation, and then return it to the gRPC framework, which sends it back tothe client.

Server-side streaming RPC

Now let’s look at one of our streaming RPCs. ListFeatures is a server-sidestreaming RPC, so we need to send back multiple Features to our client.

  1. /// ListFeatures handler. Returns a stream of features within the given
  2. /// rectangle.
  3. @override
  4. Stream<Feature> listFeatures(
  5. grpc.ServiceCall call, Rectangle request) async* {
  6. final normalizedRectangle = _normalize(request);
  7. // For each feature, check if it is in the given bounding box
  8. for (var feature in featuresDb) {
  9. if (feature.name.isEmpty) continue;
  10. final location = feature.location;
  11. if (_contains(normalizedRectangle, location)) {
  12. yield feature;
  13. }
  14. }
  15. }

As you can see, instead of getting and returning simple request and responseobjects in our method, this time we get a request object (the Rectangle inwhich our client wants to find Features) and return a Stream of Featureobjects.

In the method, we populate as many Feature objects as we need to return,adding them to the returned stream using yield. The stream is automaticallyclosed when the method returns, telling gRPC that we have finished writingresponses.

Should any error happen in this call, the error will be added as an exceptionto the stream, and the gRPC layer will translate it into an appropriate RPCstatus to be sent on the wire.

Client-side streaming RPC

Now let’s look at something a little more complicated: the client-sidestreaming method RecordRoute, where we get a stream of Points from theclient and return a single RouteSummary with information about their trip. Asyou can see, this time the request parameter is a stream, which the server canuse to both read request messages from the client. The server returns its singleresponse just like in the simple RPC case.

  1. /// RecordRoute handler. Gets a stream of points, and responds with statistics
  2. /// about the "trip": number of points, number of known features visited,
  3. /// total distance traveled, and total time spent.
  4. @override
  5. Future<RouteSummary> recordRoute(
  6. grpc.ServiceCall call, Stream<Point> request) async {
  7. int pointCount = 0;
  8. int featureCount = 0;
  9. double distance = 0.0;
  10. Point previous;
  11. final timer = Stopwatch();
  12. await for (var location in request) {
  13. if (!timer.isRunning) timer.start();
  14. pointCount++;
  15. final feature = featuresDb.firstWhere((f) => f.location == location,
  16. orElse: () => null);
  17. if (feature != null) {
  18. featureCount++;
  19. }
  20. // For each point after the first, add the incremental distance from the
  21. // previous point to the total distance value.
  22. if (previous != null) distance += _distance(previous, location);
  23. previous = location;
  24. }
  25. timer.stop();
  26. return RouteSummary()
  27. ..pointCount = pointCount
  28. ..featureCount = featureCount
  29. ..distance = distance.round()
  30. ..elapsedTime = timer.elapsed.inSeconds;
  31. }

In the method body we use await for in the request stream to repeatedly readin our client’s requests (in this case Point objects) until there are no moremessages. Once the request stream is done, the server can return itsRouteSummary.

Bidirectional streaming RPC

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

  1. /// RouteChat handler. Receives a stream of message/location pairs, and
  2. /// responds with a stream of all previous messages at each of those
  3. /// locations.
  4. @override
  5. Stream<RouteNote> routeChat(
  6. grpc.ServiceCall call, Stream<RouteNote> request) async* {
  7. await for (var note in request) {
  8. final notes = routeNotes.putIfAbsent(note.location, () => <RouteNote>[]);
  9. for (var note in notes) yield note;
  10. notes.add(note);
  11. }
  12. }

This time we get a stream of RouteNote that, as in our client-side streamingexample, can be used to read messages. However, this time we return values viaour method’s returned stream while the client is still writing messages totheir message stream.

The syntax for reading and writing here is the same as our client-streaming andserver-streaming methods. Although each side will always get the other’s messagesin the order they were written, both the client and server can read and write inany order — the streams operate completely independently.

Starting the server

Once we’ve implemented all our methods, we also need to start up a gRPC serverso that clients can actually use our service. The following snippet shows how wedo this for our RouteGuide service:

  1. Future<void> main(List<String> args) async {
  2. final server = grpc.Server([RouteGuideService()]);
  3. await server.serve(port: 8080);
  4. print('Server listening...');
  5. }

To build and start a server, we:

  • Create an instance of the gRPC server using grpc.Server(),giving a list of service implementations.
  • Call serve() on the server to start listening for requests, optionally passingin the address and port to listen on. The server will continue to serve requestsasynchronously until shutdown() is called on it.

Creating the client

In this section, we’ll look at creating a Dart client for our RouteGuideservice. You can see our complete example client code ingrpc-dart/example/route_guide/lib/src/client.dart.

Creating a stub

To call service methods, we first need to create a gRPC channel to communicatewith the server. We create this by passing the server address and port number toClientChannel() as follows:

  1. final channel = ClientChannel('127.0.0.1',
  2. port: 8080,
  3. options: const ChannelOptions(
  4. credentials: ChannelCredentials.insecure()));

You can use ChannelOptions to set TLS options (e.g., trusted certificates) forthe channel, if necessary.

Once the gRPC channel is setup, we need a client stub to perform RPCs. Weget by creating a new instance of the RouteGuideClient object provided in thepackage we generated from our .proto.

  1. final client = RouteGuideClient(channel,
  2. options: CallOptions(timeout: Duration(seconds: 30)));

You can use CallOptions to set the auth credentials (e.g., GCE credentials,JWT credentials) if the service you request requires that - however, we don’tneed to do this for our RouteGuide service.

Calling service methods

Now let’s look at how we call our service methods. Note that in gRPC-Dart, RPCsare always asynchronous, which means that the RPC returns a Future or Streamthat must be listened to, to get the response from the server or an error.

Simple RPC

Calling the simple RPC GetFeature is nearly as straightforward as calling alocal method.

  1. final point = Point()
  2. ..latitude = 409146138
  3. ..longitude = -746188906;
  4. final feature = await stub.getFeature(point));

As you can see, we call the method on the stub we got earlier. In our methodparameters we pass a request protocol buffer object (in our case Point).We can also pass an optional CallOptions object which lets us change our RPC’sbehaviour if necessary, such as time-out. If the call doesn’t return an error,the returned Future completes with the response information from the server.If there is an error, the Future will complete with the error.

Server-side streaming RPC

Here’s where we call the server-side streaming method ListFeatures, whichreturns a stream of geographical Features. If you’ve already readCreatingthe server some of this may look very familiar - streaming RPCs areimplemented in a similar way on both sides.

  1. final rect = Rectangle()...; // initialize a Rectangle
  2. try {
  3. await for (var feature in stub.listFeatures(rect)) {
  4. print(feature);
  5. }
  6. catch (e) {
  7. print('ERROR: $e');
  8. }

As in the simple RPC, we pass the method a request. However, instead of gettinga Future back, we get a Stream. The client can use the stream to read theserver’s responses.

We use await for on the returned stream to repeatedly read in the server’sresponses to a response protocol buffer object (in this case a Feature) untilthere are no more messages.

Client-side streaming RPC

The client-side streaming method RecordRoute is similar to the server-sidemethod, except that we pass the method a Stream and get a Future back.

  1. final random = Random();
  2. // Generate a number of random points
  3. Stream<Point> generateRoute(int count) async* {
  4. for (int i = 0; i < count; i++) {
  5. final point = featuresDb[random.nextInt(featuresDb.length)].location;
  6. yield point;
  7. }
  8. }
  9. final pointCount = random.nextInt(100) + 2; // Traverse at least two points
  10. final summary = await stub.recordRoute(generateRoute(pointCount));
  11. print('Route summary: $summary');

Since the generateRoute() method is async*, the points will be generated whengRPC listens to the request stream and sends the point messages to the server. Oncethe stream is done (when generateRoute() returns), gRPC knows that we’ve finishedwriting and are expecting to receive a response. The returned Future will eithercomplete with the RouteSummary message received from the server, or an error.

Bidirectional streaming RPC

Finally, let’s look at our bidirectional streaming RPC RouteChat(). As in thecase of RecordRoute, we pass the method a stream where we will write the requestmessages, and like in ListFeatures, we get back a stream that we can use to readthe response messages. However, this time we will send values via our method’s streamwhile the server is also writing messages to their message stream.

  1. Stream<RouteNote> outgoingNotes = ...;
  2. final responses = stub.routeChat(outgoingNotes);
  3. await for (var note in responses) {
  4. print('Got message ${note.message} at ${note.location.latitude}, ${note
  5. .location.longitude}');
  6. }

The syntax for reading and writing here is very similar to our client-side andserver-side streaming methods. Although each side will always get the other’smessages in the order they were written, both the client and server can read andwrite in any order — the streams operate completely independently.

Try it out!

Work from the example directory:

  1. $ cd examples/route_guide

Get packages:

  1. $ pub get

Run the server:

  1. $ dart bin/server.dart

From a different terminal, run the client:

  1. $ dart bin/client.dart

Reporting issues

If you find a problem with Dart gRPC, pleasefile an issuein our issue tracker.