Overview
gRPC can use
protocol buffers
as both its Interface Definition Language (IDL) and as its underlying message interchange format.In gRPC, a client application can directly call a method on a server application on a different machine as if it were a local object, making it easier for you to create distributed applications and services. As in many RPC systems, gRPC is based around the idea of defining a service, specifying the methods that can be called remotely with their parameters and return types. On the server side, the server implements this interface and runs a gRPC server to handle client calls. On the client side, the client has a stub (referred to as just a client in some languages) that provides the same methods as the server.
Trial
# get packages
dart pub get
# run the server
dart bin/server.dart
# open another terminal, run the client
dart bin/client.dart
Basic Tutorial
Define the Service
- simple RPC
- server-side streaming RPC
- client-side streaming RPC
- bidirectional streaming RPC
service RouteGuide {
# simple RPC
rpc GetFeature(Point) returns (Feature) {}
# server to client streaming RPC
rpc ListFeatures(Rectangle) returns (stream Feature) {}
# client to server streaming RPC
rpc RecordRoute(stream Point) returns (RouteSummary) {}
# bidirectional streaming RPC
rpm RouteChat(stream RouteNote) returns (stream RouteNote) {}
}
Create the Server
- implementing service interface generated from service definition: doing actual work of our service
- running a gRPC server to listen for requests from clients and dispatch them to the right service implementation
Start the Server
- Create instance of the gRPC server using
grpc.Server()
, giving list of service implementation - Call
serve()
on server to start lisenting for requests, optionally passing in the address and port to listen on. Server will continue to server requests async untilshutdown()
is called on it
Create the Client
- need to create gRPC
channel
to communicate with server - use
ChannelOptions
to set TLS options for the channel - need a client
stub
to perform RPCs - use
CallOptions
to set auth credentials when a service require
final channel = ClientChannel(
'127.0.0.1',
port: 8080,
options: const ChannelOptions(credentials: ChannelCredentials.insecure())
);
stub = RouteGuideClient(channel, options: CallOptions(timeout: Duration(seconds: 30)));
Comments
Join the discussion for this article at here . Our comments is using Github Issues. All of posted comments will display at this page instantly.