mirror of https://github.com/grpc/grpc.git
commit
6b10805049
357 changed files with 11409 additions and 17484 deletions
@ -0,0 +1,6 @@ |
||||
reporting: |
||||
watermarks: |
||||
statements: [80, 95] |
||||
lines: [80, 95] |
||||
functions: [80, 95] |
||||
branches: [80, 95] |
@ -0,0 +1,95 @@ |
||||
# 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. |
||||
{ |
||||
"variables" : { |
||||
'config': '<!(echo $CONFIG)' |
||||
}, |
||||
"targets" : [ |
||||
{ |
||||
'include_dirs': [ |
||||
"<!(node -e \"require('nan')\")" |
||||
], |
||||
'cflags': [ |
||||
'-std=c++0x', |
||||
'-Wall', |
||||
'-pthread', |
||||
'-g', |
||||
'-zdefs', |
||||
'-Werror', |
||||
'-Wno-error=deprecated-declarations' |
||||
], |
||||
'ldflags': [ |
||||
'-g' |
||||
], |
||||
"conditions": [ |
||||
['OS != "win"', { |
||||
'conditions': [ |
||||
['config=="gcov"', { |
||||
'cflags': [ |
||||
'-ftest-coverage', |
||||
'-fprofile-arcs', |
||||
'-O0' |
||||
], |
||||
'ldflags': [ |
||||
'-ftest-coverage', |
||||
'-fprofile-arcs' |
||||
] |
||||
} |
||||
] |
||||
] |
||||
}], |
||||
['OS == "mac"', { |
||||
'xcode_settings': { |
||||
'MACOSX_DEPLOYMENT_TARGET': '10.9', |
||||
'OTHER_CFLAGS': [ |
||||
'-std=c++11', |
||||
'-stdlib=libc++' |
||||
] |
||||
} |
||||
}] |
||||
], |
||||
"target_name": "grpc_node", |
||||
"sources": [ |
||||
"src/node/ext/byte_buffer.cc", |
||||
"src/node/ext/call.cc", |
||||
"src/node/ext/call_credentials.cc", |
||||
"src/node/ext/channel.cc", |
||||
"src/node/ext/channel_credentials.cc", |
||||
"src/node/ext/completion_queue_async_worker.cc", |
||||
"src/node/ext/node_grpc.cc", |
||||
"src/node/ext/server.cc", |
||||
"src/node/ext/server_credentials.cc", |
||||
"src/node/ext/timeval.cc" |
||||
], |
||||
"dependencies": [ |
||||
"grpc.gyp:grpc" |
||||
] |
||||
} |
||||
] |
||||
} |
@ -1,386 +1,6 @@ |
||||
#gRPC Basics: C# # |
||||
#gRPC Basics: C# sample code |
||||
|
||||
This tutorial provides a basic C# programmer's introduction to working with gRPC. By walking through this example you'll learn how to: |
||||
The files in this folder are the samples used in [gRPC Basics: C#][], |
||||
a detailed tutorial for using gRPC in C#. |
||||
|
||||
- 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 only uses the proto2 version of the protocol buffers language, as proto3 support for C# is not ready yet (see [protobuf C# README](https://github.com/google/protobuf/tree/master/csharp#proto2--proto3)). |
||||
|
||||
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/csharp/route_guide](.). To download the example, clone this repository by running the following command: |
||||
```shell |
||||
$ git clone https://github.com/grpc/grpc.git |
||||
``` |
||||
|
||||
All the files for this tutorial are in the directory `examples/csharp/route_guide`. |
||||
Open the solution `examples/csharp/route_guide/RouteGuide.sln` from Visual Studio (or Monodevelop on Linux). |
||||
|
||||
On Windows, you should not need to do anything besides opening the solution. All the needed dependencies will be restored |
||||
for you automatically by the `Grpc` NuGet package upon building the solution. |
||||
|
||||
On Linux (or MacOS), you will first need to install protobuf and gRPC C Core using Linuxbrew (or Homebrew) tool in order to be |
||||
able to generate the server and client interface code and run the examples. Follow the instructions for [Linux](https://github.com/grpc/grpc/tree/master/src/csharp#usage-linux-mono) or [MacOS](https://github.com/grpc/grpc/tree/master/src/csharp#usage-macos-mono). |
||||
|
||||
## Defining the service |
||||
|
||||
Our first step (as you'll know from [Getting started](https://github.com/grpc/grpc/tree/master/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 [`RouteGuide/protos/route_guide.proto`](RouteGuide/protos/route_guide.proto). |
||||
|
||||
To define a service, you specify a named `service` in your .proto file: |
||||
|
||||
```protobuf |
||||
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. |
||||
```protobuf |
||||
// 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. |
||||
```protobuf |
||||
// 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 server-side streaming method by placing the `stream` keyword before the *request* type. |
||||
```protobuf |
||||
// 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. |
||||
```protobuf |
||||
// 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: |
||||
```protobuf |
||||
// 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. |
||||
|
||||
If you want to run this yourself, make sure you've installed protoc and gRPC C# plugin. The instructions vary based on your OS: |
||||
- For Windows, the `Grpc.Tools` and `Google.Protobuf` NuGet packages contain the binaries you will need to generate the code. |
||||
- For Linux, make sure you've [installed gRPC C Core using Linuxbrew](https://github.com/grpc/grpc/tree/master/src/csharp#usage-linux-mono) |
||||
- For MacOS, make sure you've [installed gRPC C Core using Homebrew](https://github.com/grpc/grpc/tree/master/src/csharp#usage-macos-mono) |
||||
|
||||
Once that's done, the following command can be used to generate the C# code. |
||||
|
||||
To generate the code on Windows, we use `protoc.exe` from the `Google.Protobuf` NuGet package and `grpc_csharp_plugin.exe` from the `Grpc.Tools` NuGet package (both under the `tools` directory). |
||||
Normally you would need to add the `Grpc.Tools` package to the solution yourself, but in this tutorial it has been already done for you. Following command should be run from the `csharp/route_guide` directory: |
||||
``` |
||||
> packages\Google.Protobuf.3.0.0-alpha4\tools\protoc -I RouteGuide/protos --csharp_out=RouteGuide --grpc_out=RouteGuide --plugin=protoc-gen-grpc=packages\Grpc.Tools.0.7.0\tools\grpc_csharp_plugin.exe RouteGuide/protos/route_guide.proto |
||||
``` |
||||
|
||||
On Linux/MacOS, we rely on `protoc` and `grpc_csharp_plugin` being installed by Linuxbrew/Homebrew. Run this command from the route_guide directory: |
||||
```shell |
||||
$ protoc -I RouteGuide/protos --csharp_out=RouteGuide --grpc_out=RouteGuide --plugin=protoc-gen-grpc=`which grpc_csharp_plugin` RouteGuide/protos/route_guide.proto |
||||
``` |
||||
|
||||
Running one of the previous commands regenerates the following files in the RouteGuide directory: |
||||
- `RouteGuide/RouteGuide.cs` defines a namespace `examples` |
||||
- This contains all the protocol buffer code to populate, serialize, and retrieve our request and response message types |
||||
- `RouteGuide/RouteGuideGrpc.cs`, provides stub and service classes |
||||
- an interface `RouteGuide.IRouteGuide` to inherit from when defining RouteGuide service implementations |
||||
- a class `RouteGuide.RouteGuideClient` that can be used to access remote RouteGuide instances |
||||
|
||||
|
||||
<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 [RouteGuideServer/RouteGuideImpl.cs](RouteGuideServer/RouteGuideServerImpl.cs). 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.IRouteGuide`: |
||||
|
||||
```csharp |
||||
// RouteGuideImpl provides an implementation of the RouteGuide service. |
||||
public class RouteGuideImpl : RouteGuide.IRouteGuide |
||||
``` |
||||
|
||||
#### Simple RPC |
||||
|
||||
`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`. |
||||
|
||||
```csharp |
||||
public Task<Feature> GetFeature(Point request, Grpc.Core.ServerCallContext context) |
||||
{ |
||||
return Task.FromResult(CheckFeature(request)); |
||||
} |
||||
``` |
||||
|
||||
The method is passed a context for the RPC (which is empty in the alpha release), the client's `Point` protocol buffer request, and returns a `Feature` protocol buffer. In the method we create the `Feature` with the appropriate information, and then return it. To allow asynchronous |
||||
implementation, the method returns `Task<Feature>` rather than just `Feature`. You are free to perform your computations synchronously and return |
||||
the result once you've finished, just as we do in the example. |
||||
|
||||
#### Server-side streaming RPC |
||||
|
||||
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` protocol buffers to our client. |
||||
|
||||
```csharp |
||||
// in RouteGuideImpl |
||||
public async Task ListFeatures(Rectangle request, |
||||
Grpc.Core.IServerStreamWriter<Feature> responseStream, |
||||
Grpc.Core.ServerCallContext context) |
||||
{ |
||||
var responses = features.FindAll( (feature) => feature.Exists() && request.Contains(feature.Location) ); |
||||
foreach (var response in responses) |
||||
{ |
||||
await responseStream.WriteAsync(response); |
||||
} |
||||
} |
||||
``` |
||||
|
||||
As you can see, here the request object is a `Rectangle` in which our client wants to find `Feature`s, but instead of returning a simple response we need to write responses to an asynchronous stream `IServerStreamWriter` using async method `WriteAsync`. |
||||
|
||||
#### Client-side streaming RPC |
||||
|
||||
Similarly, the client-side streaming method `RecordRoute` uses an [IAsyncEnumerator](https://github.com/Reactive-Extensions/Rx.NET/blob/master/Ix.NET/Source/System.Interactive.Async/IAsyncEnumerator.cs), to read the stream of requests using the async method `MoveNext` and the `Current` property. |
||||
|
||||
```csharp |
||||
public async Task<RouteSummary> RecordRoute(Grpc.Core.IAsyncStreamReader<Point> requestStream, |
||||
Grpc.Core.ServerCallContext context) |
||||
{ |
||||
int pointCount = 0; |
||||
int featureCount = 0; |
||||
int distance = 0; |
||||
Point previous = null; |
||||
var stopwatch = new Stopwatch(); |
||||
stopwatch.Start(); |
||||
|
||||
while (await requestStream.MoveNext()) |
||||
{ |
||||
var point = requestStream.Current; |
||||
pointCount++; |
||||
if (CheckFeature(point).Exists()) |
||||
{ |
||||
featureCount++; |
||||
} |
||||
if (previous != null) |
||||
{ |
||||
distance += (int) previous.GetDistance(point); |
||||
} |
||||
previous = point; |
||||
} |
||||
|
||||
stopwatch.Stop(); |
||||
|
||||
return new RouteSummary |
||||
{ |
||||
PointCount = pointCount, |
||||
FeatureCount = featureCount, |
||||
Distance = distance, |
||||
ElapsedTime = (int)(stopwatch.ElapsedMilliseconds / 1000) |
||||
}; |
||||
} |
||||
``` |
||||
|
||||
#### Bidirectional streaming RPC |
||||
|
||||
Finally, let's look at our bidirectional streaming RPC `RouteChat`. |
||||
|
||||
```csharp |
||||
public async Task RouteChat(Grpc.Core.IAsyncStreamReader<RouteNote> requestStream, |
||||
Grpc.Core.IServerStreamWriter<RouteNote> responseStream, |
||||
Grpc.Core.ServerCallContext context,) |
||||
{ |
||||
while (await requestStream.MoveNext()) |
||||
{ |
||||
var note = requestStream.Current; |
||||
List<RouteNote> prevNotes = AddNoteForLocation(note.Location, note); |
||||
foreach (var prevNote in prevNotes) |
||||
{ |
||||
await responseStream.WriteAsync(prevNote); |
||||
} |
||||
} |
||||
} |
||||
``` |
||||
|
||||
Here the method receives both `requestStream` and `responseStream` arguments. Reading the requests is done the same way as in the client-side streaming method `RecordRoute`. Writing the responses is done the same way as in the server-side streaming method `ListFeatures`. |
||||
|
||||
### 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: |
||||
|
||||
```csharp |
||||
var features = RouteGuideUtil.ParseFeatures(RouteGuideUtil.DefaultFeaturesFile); |
||||
|
||||
Server server = new Server |
||||
{ |
||||
Services = { RouteGuide.BindService(new RouteGuideImpl(features)) }, |
||||
Ports = { new ServerPort("localhost", Port, ServerCredentials.Insecure) } |
||||
}; |
||||
server.Start(); |
||||
|
||||
Console.WriteLine("RouteGuide server listening on port " + port); |
||||
Console.WriteLine("Press any key to stop the server..."); |
||||
Console.ReadKey(); |
||||
|
||||
server.ShutdownAsync().Wait(); |
||||
``` |
||||
As you can see, we build and start our server using `Grpc.Core.Server` class. To do this, we: |
||||
|
||||
1. Create an instance of `Grpc.Core.Server`. |
||||
1. Create an instance of our service implementation class `RouteGuideImpl`. |
||||
3. Register our service implementation by adding its service definition to `Services` collection (We obtain the service definition from the generated `RouteGuide.BindService` method). |
||||
2. Specify the address and port we want to use to listen for client requests. This is done by adding `ServerPort` to `Ports` collection. |
||||
4. Call `Start` on the server instance to start an RPC server for our service. |
||||
|
||||
<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 [RouteGuideClient/Program.cs](RouteGuideClient/Program.cs). |
||||
|
||||
### Creating a stub |
||||
|
||||
To call service methods, we first need to create a *stub*. |
||||
|
||||
First, we need to create a gRPC client channel that will connect to gRPC server. Then, we use the `RouteGuide.NewClient` method of the `RouteGuide` class generated from our .proto. |
||||
|
||||
```csharp |
||||
Channel channel = new Channel("127.0.0.1:50052", Credentials.Insecure) |
||||
var client = new RouteGuideClient(RouteGuide.NewClient(channel)); |
||||
|
||||
// YOUR CODE GOES HERE |
||||
|
||||
channel.ShutdownAsync().Wait(); |
||||
``` |
||||
|
||||
### Calling service methods |
||||
|
||||
Now let's look at how we call our service methods. gRPC C# provides asynchronous versions of each of the supported method types. For convenience, |
||||
gRPC C# also provides a synchronous method stub, but only for simple (single request/single response) RPCs. |
||||
|
||||
#### Simple RPC |
||||
|
||||
Calling the simple RPC `GetFeature` in a synchronous way is nearly as straightforward as calling a local method. |
||||
|
||||
```csharp |
||||
Point request = new Point { Latitude = 409146138, Longitude = -746188906 }; |
||||
Feature feature = client.GetFeature(request); |
||||
``` |
||||
|
||||
As you can see, we create and populate a request protocol buffer object (in our case `Point`), and call the desired method on the client object, passing it the request. If the RPC finishes with success, the response protocol buffer (in our case `Feature`) will be returned. Otherwise, an exception of type `RpcException` will be thrown, indicating the status code of the problem. |
||||
|
||||
Alternatively, if you are in async context, you can call an asynchronous version of the method (and use `await` keyword to await the result): |
||||
```csharp |
||||
Point request = new Point { Latitude = 409146138, Longitude = -746188906 }; |
||||
Feature feature = await client.GetFeatureAsync(request); |
||||
``` |
||||
|
||||
#### 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. The difference with respect to simple call is that the client methods return an instance of a call object, that provides access to request/response streams and/or asynchronous result (depending on the streaming type you are using). |
||||
|
||||
Here's where we call the server-side streaming method `ListFeatures`, which has property `ReponseStream` of type `IAsyncEnumerator<Feature>` |
||||
|
||||
```csharp |
||||
using (var call = client.ListFeatures(request)) |
||||
{ |
||||
while (await call.ResponseStream.MoveNext()) |
||||
{ |
||||
Feature feature = call.ResponseStream.Current; |
||||
Console.WriteLine("Received " + feature.ToString()); |
||||
} |
||||
} |
||||
``` |
||||
|
||||
The client-side streaming method `RecordRoute` is similar, except we use the property `RequestStream` to write the requests one by one using `WriteAsync` and eventually signal that no more request will be send using `CompleteAsync`. The method result can be obtained through the property |
||||
`ResponseAsync`. |
||||
```csharp |
||||
using (var call = client.RecordRoute()) |
||||
{ |
||||
foreach (var point in points) |
||||
{ |
||||
await call.RequestStream.WriteAsync(point); |
||||
} |
||||
await call.RequestStream.CompleteAsync(); |
||||
|
||||
RouteSummary summary = await call.ResponseAsync; |
||||
} |
||||
``` |
||||
|
||||
Finally, let's look at our bidirectional streaming RPC `RouteChat`. In this case, we write the request to `RequestStream` and receive the responses from `ResponseStream`. As you can see from the example, the streams are independent of each other. |
||||
|
||||
```csharp |
||||
using (var call = client.RouteChat()) |
||||
{ |
||||
var responseReaderTask = Task.Run(async () => |
||||
{ |
||||
while (await call.ResponseStream.MoveNext()) |
||||
{ |
||||
var note = call.ResponseStream.Current; |
||||
Console.WriteLine("Received " + note); |
||||
} |
||||
}); |
||||
|
||||
foreach (RouteNote request in requests) |
||||
{ |
||||
await call.RequestStream.WriteAsync(request); |
||||
} |
||||
await call.RequestStream.CompleteAsync(); |
||||
await responseReaderTask; |
||||
} |
||||
``` |
||||
|
||||
## Try it out! |
||||
|
||||
Build client and server: |
||||
|
||||
Open the solution `examples/csharp/route_guide/RouteGuide.sln` from Visual Studio (or Monodevelop on Linux) and hit "Build". |
||||
|
||||
Run the server, which will listen on port 50052: |
||||
``` |
||||
> cd RouteGuideServer/bin/Debug |
||||
> RouteGuideServer.exe |
||||
``` |
||||
|
||||
Run the client (in a different terminal): |
||||
``` |
||||
> cd RouteGuideClient/bin/Debug |
||||
> RouteGuideClient.exe |
||||
``` |
||||
|
||||
You can also run the server and client directly from Visual Studio. |
||||
|
||||
On Linux or Mac, use `mono RouteGuideServer.exe` and `mono RouteGuideClient.exe` to run the server and client. |
||||
[gRPC Basics: C#]:http://www.grpc.io/docs/tutorials/basic/csharp.html |
||||
|
@ -1,10 +0,0 @@ |
||||
{ |
||||
"name": "grpc-demo", |
||||
"version": "0.5.0", |
||||
"dependencies": { |
||||
"async": "^0.9.0", |
||||
"grpc": "~0.11.0", |
||||
"minimist": "^1.1.0", |
||||
"underscore": "^1.8.2" |
||||
} |
||||
} |
@ -1,363 +1,5 @@ |
||||
#gRPC Basics: Node.js |
||||
#gRPC Basics: Node.js sample code |
||||
|
||||
This tutorial provides a basic Node.js programmer's introduction to working with gRPC. By walking through this example you'll learn how to: |
||||
The files in this folder are the samples used in [gRPC Basics: Node.js][], a detailed tutorial for using gRPC in Node.js. |
||||
|
||||
- Define a service in a .proto file. |
||||
- Use the Node.js 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 Node.js: 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/node/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/node/route_guide`: |
||||
```shell |
||||
$ cd examples/node/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 Node.js quick start guide](..). |
||||
|
||||
|
||||
## Defining the service |
||||
|
||||
Our first step (as you'll know from [Getting started](https://github.com/grpc/grpc/tree/master/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`](../../route_guide.proto). |
||||
|
||||
To define a service, you specify a named `service` in your .proto file: |
||||
|
||||
```protobuf |
||||
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. |
||||
```protobuf |
||||
// 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. |
||||
```protobuf |
||||
// 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 server-side streaming method by placing the `stream` keyword before the *request* type. |
||||
```protobuf |
||||
// 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. |
||||
```protobuf |
||||
// 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: |
||||
```protobuf |
||||
// 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; |
||||
} |
||||
``` |
||||
|
||||
|
||||
## Loading service descriptors from proto files |
||||
|
||||
The Node.js library dynamically generates service descriptors and client stub definitions from `.proto` files loaded at runtime. |
||||
|
||||
To load a `.proto` file, simply `require` the gRPC library, then use its `load()` method: |
||||
|
||||
```node |
||||
var grpc = require('grpc'); |
||||
var protoDescriptor = grpc.load(__dirname + '/route_guide.proto'); |
||||
// The protoDescriptor object has the full package hierarchy |
||||
var example = protoDescriptor.routeguide; |
||||
``` |
||||
|
||||
Once you've done this, the stub constructor is in the `routeguide` namespace (`protoDescriptor.routeguide.RouteGuide`) and the service descriptor (which is used to create a server) is a property of the stub (`protoDescriptor.routeguide.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 [route_guide_server.js](route_guide_server.js). Let's take a closer look at how it works. |
||||
|
||||
### Implementing RouteGuide |
||||
|
||||
As you can see, our server has a `Server` constructor generated from the `RouteGuide.service` descriptor object |
||||
|
||||
```node |
||||
var Server = grpc.buildServer([routeguide.RouteGuide.service]); |
||||
``` |
||||
In this case we're implementing the *asynchronous* version of `RouteGuide`, which provides our default gRPC server behaviour. |
||||
|
||||
The functions in `route_guide_server.js` implement 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`. |
||||
|
||||
```node |
||||
function checkFeature(point) { |
||||
var feature; |
||||
// Check if there is already a feature object for the given point |
||||
for (var i = 0; i < feature_list.length; i++) { |
||||
feature = feature_list[i]; |
||||
if (feature.location.latitude === point.latitude && |
||||
feature.location.longitude === point.longitude) { |
||||
return feature; |
||||
} |
||||
} |
||||
var name = ''; |
||||
feature = { |
||||
name: name, |
||||
location: point |
||||
}; |
||||
return feature; |
||||
} |
||||
function getFeature(call, callback) { |
||||
callback(null, checkFeature(call.request)); |
||||
} |
||||
``` |
||||
|
||||
The method is passed a call object for the RPC, which has the `Point` parameter as a property, and a callback to which we can pass our returned `Feature`. In the method body we populate a `Feature` corresponding to the given point and pass it to the callback, with a null first parameter to indicate that there is no error. |
||||
|
||||
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. |
||||
|
||||
```node |
||||
function listFeatures(call) { |
||||
var lo = call.request.lo; |
||||
var hi = call.request.hi; |
||||
var left = _.min([lo.longitude, hi.longitude]); |
||||
var right = _.max([lo.longitude, hi.longitude]); |
||||
var top = _.max([lo.latitude, hi.latitude]); |
||||
var bottom = _.min([lo.latitude, hi.latitude]); |
||||
// For each feature, check if it is in the given bounding box |
||||
_.each(feature_list, function(feature) { |
||||
if (feature.name === '') { |
||||
return; |
||||
} |
||||
if (feature.location.longitude >= left && |
||||
feature.location.longitude <= right && |
||||
feature.location.latitude >= bottom && |
||||
feature.location.latitude <= top) { |
||||
call.write(feature); |
||||
} |
||||
}); |
||||
call.end(); |
||||
} |
||||
``` |
||||
|
||||
As you can see, instead of getting the call object and callback in our method parameters, this time we get a `call` object that implements the `Writable` interface. In the method, we create as many `Feature` objects as we need to return, writing them to the `call` using its `write()` method. Finally, we call `call.end()` to indicate that we have sent all messages. |
||||
|
||||
If you look at the client-side streaming method `RecordRoute` you'll see it's quite similar to the unary call, except this time the `call` parameter implements the `Reader` interface. The `call`'s `'data'` event fires every time there is new data, and the `'end'` event fires when all data has been read. Like the unary case, we respond by calling the callback |
||||
|
||||
```node |
||||
call.on('data', function(point) { |
||||
// Process user data |
||||
}); |
||||
call.on('end', function() { |
||||
callback(null, result); |
||||
}); |
||||
``` |
||||
|
||||
Finally, let's look at our bidirectional streaming RPC `RouteChat()`. |
||||
|
||||
```node |
||||
function routeChat(call) { |
||||
call.on('data', function(note) { |
||||
var key = pointKey(note.location); |
||||
/* For each note sent, respond with all previous notes that correspond to |
||||
* the same point */ |
||||
if (route_notes.hasOwnProperty(key)) { |
||||
_.each(route_notes[key], function(note) { |
||||
call.write(note); |
||||
}); |
||||
} else { |
||||
route_notes[key] = []; |
||||
} |
||||
// Then add the new note to the list |
||||
route_notes[key].push(JSON.parse(JSON.stringify(note))); |
||||
}); |
||||
call.on('end', function() { |
||||
call.end(); |
||||
}); |
||||
} |
||||
``` |
||||
|
||||
This time we get a `call` implementing `Duplex` 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: |
||||
|
||||
```node |
||||
function getServer() { |
||||
var server = new grpc.Server(); |
||||
server.addProtoService(routeguide.RouteGuide.service, { |
||||
getFeature: getFeature, |
||||
listFeatures: listFeatures, |
||||
recordRoute: recordRoute, |
||||
routeChat: routeChat |
||||
}); |
||||
return server; |
||||
} |
||||
var routeServer = getServer(); |
||||
routeServer.bind('0.0.0.0:50051', grpc.ServerCredentials.createInsecure()); |
||||
routeServer.start(); |
||||
``` |
||||
|
||||
As you can see, we build and start our server with the following steps: |
||||
|
||||
1. Create a `Server` constructor from the `RouteGuide` service descriptor. |
||||
2. Implement the service methods. |
||||
3. Create an instance of the server by calling the `Server` constructor with the method implementations. |
||||
4. Specify the address and port we want to use to listen for client requests using the instance's `bind()` method. |
||||
5. Call `listen()` on the instance to start the RPC server. |
||||
|
||||
<a name="client"></a> |
||||
## Creating the client |
||||
|
||||
In this section, we'll look at creating a Node.js client for our `RouteGuide` service. You can see our complete example client code in [route_guide_client.js](route_guide_client.js). |
||||
|
||||
### Creating a stub |
||||
|
||||
To call service methods, we first need to create a *stub*. To do this, we just need to call the RouteGuide stub constructor, specifying the server address and port. |
||||
|
||||
```node |
||||
var client = new routeguide.RouteGuide('localhost:50051', |
||||
grpc.Credentials.createInsecure()); |
||||
``` |
||||
|
||||
### Calling service methods |
||||
|
||||
Now let's look at how we call our service methods. Note that all of these methods are asynchronous: they use either events or callbacks to retrieve results. |
||||
|
||||
#### Simple RPC |
||||
|
||||
Calling the simple RPC `GetFeature` is nearly as straightforward as calling a local asynchronous method. |
||||
|
||||
```node |
||||
var point = {latitude: 409146138, longitude: -746188906}; |
||||
stub.getFeature(point, function(err, feature) { |
||||
if (err) { |
||||
// process error |
||||
} else { |
||||
// process feature |
||||
} |
||||
}); |
||||
``` |
||||
|
||||
As you can see, we create and populate a request object. Finally, we call the method on the stub, passing it the request and callback. If there is no error, then we can read the response information from the server from our response object. |
||||
|
||||
```node |
||||
console.log('Found feature called "' + feature.name + '" at ' + |
||||
feature.location.latitude/COORD_FACTOR + ', ' + |
||||
feature.location.longitude/COORD_FACTOR); |
||||
``` |
||||
|
||||
#### 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: |
||||
|
||||
```node |
||||
var call = client.listFeatures(rectangle); |
||||
call.on('data', function(feature) { |
||||
console.log('Found feature called "' + feature.name + '" at ' + |
||||
feature.location.latitude/COORD_FACTOR + ', ' + |
||||
feature.location.longitude/COORD_FACTOR); |
||||
}); |
||||
call.on('end', function() { |
||||
// The server has finished sending |
||||
}); |
||||
call.on('status', function(status) { |
||||
// process status |
||||
}); |
||||
``` |
||||
|
||||
Instead of passing the method a request and callback, we pass it a request and get a `Readable` stream object back. The client can use the `Readable`'s `'data'` event to read the server's responses. This event fires with each `Feature` message object until there are no more messages: the `'end'` event indicates that the call is done. Finally, the status event fires when the server sends the status. |
||||
|
||||
The client-side streaming method `RecordRoute` is similar, except there we pass the method a callback and get back a `Writable`. |
||||
|
||||
```node |
||||
var call = client.recordRoute(function(error, stats) { |
||||
if (error) { |
||||
callback(error); |
||||
} |
||||
console.log('Finished trip with', stats.point_count, 'points'); |
||||
console.log('Passed', stats.feature_count, 'features'); |
||||
console.log('Travelled', stats.distance, 'meters'); |
||||
console.log('It took', stats.elapsed_time, 'seconds'); |
||||
}); |
||||
function pointSender(lat, lng) { |
||||
return function(callback) { |
||||
console.log('Visiting point ' + lat/COORD_FACTOR + ', ' + |
||||
lng/COORD_FACTOR); |
||||
call.write({ |
||||
latitude: lat, |
||||
longitude: lng |
||||
}); |
||||
_.delay(callback, _.random(500, 1500)); |
||||
}; |
||||
} |
||||
var point_senders = []; |
||||
for (var i = 0; i < num_points; i++) { |
||||
var rand_point = feature_list[_.random(0, feature_list.length - 1)]; |
||||
point_senders[i] = pointSender(rand_point.location.latitude, |
||||
rand_point.location.longitude); |
||||
} |
||||
async.series(point_senders, function() { |
||||
call.end(); |
||||
}); |
||||
``` |
||||
|
||||
Once we've finished writing our client's requests to the stream using `write()`, we need to call `end()` on the stream to let gRPC know that we've finished writing. If the status is `OK`, the `stats` object 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 `Duplex` stream object, which we can use to both write and read messages. |
||||
|
||||
```node |
||||
var call = client.routeChat(); |
||||
``` |
||||
|
||||
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 |
||||
$ npm install |
||||
``` |
||||
Run the server, which will listen on port 50051: |
||||
```shell |
||||
$ node ./route_guide_server.js --db_path=route_guide_db.json |
||||
``` |
||||
Run the client (in a different terminal): |
||||
```shell |
||||
$ node ./route_guide_client.js --db_path=route_guide_db.json |
||||
``` |
||||
[gRPC Basics: Node.js]:http://www.grpc.io/docs/tutorials/basic/node.html |
||||
|
@ -1,262 +1,6 @@ |
||||
#gRPC Basics: PHP |
||||
#gRPC Basics: PHP sample code |
||||
|
||||
This tutorial provides a basic PHP programmer's introduction to working with gRPC. By walking through this example you'll learn how to: |
||||
The files in this folder are the samples used in [gRPC Basics: PHP][], |
||||
a detailed tutorial for using gRPC in Ruby. |
||||
|
||||
- Define a service in a .proto file. |
||||
- Generate client code using the protocol buffer compiler. |
||||
- Use the PHP gRPC API to write a simple client for your service. |
||||
|
||||
It assumes a passing familiarity with [protocol buffers](https://developers.google.com/protocol-buffers/docs/overview). Note that the example in this tutorial uses the proto2 version of the protocol buffers language. |
||||
|
||||
Also note that currently you can only create clients in PHP for gRPC services - you can find out how to create gRPC servers in our other tutorials, e.g. [Node.js](../node/route_guide). |
||||
|
||||
This isn't a comprehensive guide to using gRPC in PHP: more reference documentation is coming soon. |
||||
|
||||
- [Why use gRPC?](#why-grpc) |
||||
- [Example code and setup](#setup) |
||||
- [Try it out!](#try) |
||||
- [Defining the service](#proto) |
||||
- [Generating client code](#protoc) |
||||
- [Creating the client](#client) |
||||
|
||||
|
||||
<a name="why-grpc"></a> |
||||
## Why use gRPC? |
||||
|
||||
With gRPC you can define your 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. You also get all the advantages of working with protocol buffers, including efficient serialization, a simple IDL, and easy interface updating. |
||||
|
||||
|
||||
<a name="setup"></a> |
||||
## Example code and setup |
||||
|
||||
The example code for our tutorial is in [examples/php/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/php/route_guide`: |
||||
```shell |
||||
$ cd examples/php/route_guide |
||||
``` |
||||
|
||||
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. |
||||
|
||||
You also should have the relevant tools installed to generate the client interface code (and a server in another language, for testing). You can obtain the latter by following [these setup instructions](https://github.com/grpc/homebrew-grpc). |
||||
|
||||
|
||||
<a name="try"></a> |
||||
## Try it out! |
||||
|
||||
To try the sample app, we need a gRPC server running locally. Let's compile and run, for example, the Node.js server in this repository: |
||||
|
||||
```shell |
||||
$ cd ../../node |
||||
$ npm install |
||||
$ cd route_guide |
||||
$ nodejs ./route_guide_server.js --db_path=route_guide_db.json |
||||
``` |
||||
|
||||
Run the PHP client (in a different terminal): |
||||
|
||||
```shell |
||||
$ ./run_route_guide_client.sh |
||||
``` |
||||
|
||||
The next sections guide you step-by-step through how this proto service is defined, how to generate a client library from it, and how to create a client stub that uses that library. |
||||
|
||||
|
||||
<a name="proto"></a> |
||||
## Defining the service |
||||
|
||||
First let's look at how the service we're using is defined. A gRPC *service* and its method *request* and *response* types using [protocol buffers](https://developers.google.com/protocol-buffers/docs/overview). You can see the complete .proto file for our example in [`route_guide.proto`](route_guide.proto). |
||||
|
||||
To define a service, you specify a named `service` in your .proto file: |
||||
|
||||
```protobuf |
||||
service RouteGuide { |
||||
... |
||||
} |
||||
``` |
||||
|
||||
Then you define `rpc` methods inside your service definition, specifying their request and response types. Protocol buffers let 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 and receives a response later, just like a normal remote procedure call. |
||||
```protobuf |
||||
// Obtains the feature at a given position. |
||||
rpc GetFeature(Point) returns (Feature) {} |
||||
``` |
||||
|
||||
- A *response-streaming RPC* where the client sends a request to the server and gets back a stream of response messages. You specify a response-streaming method by placing the `stream` keyword before the *response* type. |
||||
```protobuf |
||||
// 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 *request-streaming RPC* where the client sends a sequence of messages to the server. Once the client has finished writing the messages, it waits for the server to read them all and return its response. You specify a request-streaming method by placing the `stream` keyword before the *request* type. |
||||
```protobuf |
||||
// 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 to the other. 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. |
||||
```protobuf |
||||
// 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: |
||||
```protobuf |
||||
// 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; |
||||
} |
||||
``` |
||||
|
||||
|
||||
<a name="protoc"></a> |
||||
## Generating client code |
||||
|
||||
The PHP client stub implementation of the proto files can be generated by the [`protoc-gen-php`](https://github.com/datto/protobuf-php) tool. To install the tool: |
||||
|
||||
```sh |
||||
$ cd examples/php |
||||
$ php composer.phar install |
||||
$ cd vendor/datto/protobuf-php |
||||
$ gem install rake ronn |
||||
$ rake pear:package version=1.0 |
||||
$ sudo pear install Protobuf-1.0.tgz |
||||
``` |
||||
|
||||
To generate the client stub implementation .php file: |
||||
|
||||
```sh |
||||
$ cd php/route_guide |
||||
$ protoc-gen-php -i . -o . ./route_guide.proto |
||||
``` |
||||
|
||||
A `route_guide.php` file will be generated in the `php/route_guide` directory. You do not need to modify the file. |
||||
|
||||
To load the generated client stub file, simply `require` it in your PHP application: |
||||
|
||||
```php |
||||
require dirname(__FILE__) . '/route_guide.php'; |
||||
``` |
||||
|
||||
The file contains: |
||||
- All the protocol buffer code to populate, serialize, and retrieve our request and response message types. |
||||
- A class called `routeguide\RouteGuideClient` that lets clients call the methods defined in the `RouteGuide` service. |
||||
|
||||
|
||||
<a name="client"></a> |
||||
## Creating the client |
||||
|
||||
In this section, we'll look at creating a PHP client for our `RouteGuide` service. You can see our complete example client code in [route_guide_client.php](route_guide_client.php). |
||||
|
||||
### Constructing a client object |
||||
|
||||
To call service methods, we first need to create a client object, an instance of the generated `RouteGuideClient` class. The constructor of the class expects the server address and port we want to connect to: |
||||
|
||||
```php |
||||
$client = new routeguide\RouteGuideClient(new Grpc\BaseStub('localhost:50051', [])); |
||||
``` |
||||
|
||||
### Calling service methods |
||||
|
||||
Now let's look at how we call our service methods. |
||||
|
||||
#### Simple RPC |
||||
|
||||
Calling the simple RPC `GetFeature` is nearly as straightforward as calling a local asynchronous method. |
||||
|
||||
```php |
||||
$point = new routeguide\Point(); |
||||
$point->setLatitude(409146138); |
||||
$point->setLongitude(-746188906); |
||||
list($feature, $status) = $client->GetFeature($point)->wait(); |
||||
``` |
||||
|
||||
As you can see, we create and populate a request object, i.e. an `routeguide\Point` object. Then, we call the method on the stub, passing it the request object. If there is no error, then we can read the response information from the server from our response object, i.e. an `routeguide\Feature` object. |
||||
|
||||
```php |
||||
print sprintf("Found %s \n at %f, %f\n", $feature->getName(), |
||||
$feature->getLocation()->getLatitude() / COORD_FACTOR, |
||||
$feature->getLocation()->getLongitude() / COORD_FACTOR); |
||||
``` |
||||
|
||||
#### Streaming RPCs |
||||
|
||||
Now let's look at our streaming methods. Here's where we call the server-side streaming method `ListFeatures`, which returns a stream of geographical `Feature`s: |
||||
|
||||
```php |
||||
$lo_point = new routeguide\Point(); |
||||
$hi_point = new routeguide\Point(); |
||||
|
||||
$lo_point->setLatitude(400000000); |
||||
$lo_point->setLongitude(-750000000); |
||||
$hi_point->setLatitude(420000000); |
||||
$hi_point->setLongitude(-730000000); |
||||
|
||||
$rectangle = new routeguide\Rectangle(); |
||||
$rectangle->setLo($lo_point); |
||||
$rectangle->setHi($hi_point); |
||||
|
||||
$call = $client->ListFeatures($rectangle); |
||||
// an iterator over the server streaming responses |
||||
$features = $call->responses(); |
||||
foreach ($features as $feature) { |
||||
// process each feature |
||||
} // the loop will end when the server indicates there is no more responses to be sent. |
||||
``` |
||||
|
||||
The `$call->responses()` method call returns an iterator. When the server sends a response, a `$feature` object will be returned in the `foreach` loop, until the server indiciates that there will be no more responses to be sent. |
||||
|
||||
The client-side streaming method `RecordRoute` is similar, except there we pass the method an iterator and get back a `routeguide\RouteSummary`. |
||||
|
||||
```php |
||||
$points_iter = function($db) { |
||||
for ($i = 0; $i < $num_points; $i++) { |
||||
$point = new routeguide\Point(); |
||||
$point->setLatitude($lat); |
||||
$point->setLongitude($long); |
||||
yield $point; |
||||
} |
||||
}; |
||||
// $points_iter is an iterator simulating client streaming |
||||
list($route_summary, $status) = |
||||
$client->RecordRoute($points_iter($db))->wait(); |
||||
``` |
||||
|
||||
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 `BidiStreamingCall` stream object, which we can use to both write and read messages. |
||||
|
||||
```php |
||||
$call = $client->RouteChat(); |
||||
``` |
||||
|
||||
To write messages from the client: |
||||
|
||||
```php |
||||
foreach ($notes as $n) { |
||||
$route_note = new routerguide\RouteNote(); |
||||
$call->write($route_note); |
||||
} |
||||
$call->writesDone(); |
||||
``` |
||||
|
||||
To read messages from the server: |
||||
|
||||
```php |
||||
while ($route_note_reply = $call->read()) { |
||||
// process $route_note_reply |
||||
} |
||||
``` |
||||
|
||||
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. |
||||
[gRPC Basics: PHP]:http://www.grpc.io/docs/tutorials/basic/php.html |
||||
|
@ -0,0 +1,55 @@ |
||||
gRPC in 3 minutes (Python) |
||||
======================== |
||||
|
||||
Background |
||||
------------- |
||||
For this sample, we've already generated the server and client stubs from |
||||
[helloworld.proto][] and we'll be using a specific reference platform. |
||||
|
||||
Prerequisites |
||||
------------- |
||||
|
||||
- Debian 8.2 "Jessie" platform with `root` access |
||||
- `git` |
||||
- `python2.7` |
||||
- `pip` |
||||
- Python development headers |
||||
|
||||
Set-up |
||||
------- |
||||
```sh |
||||
$ # install the gRPC Core: |
||||
$ sudo apt-get install libgrpc-dev |
||||
$ # install gRPC Python: |
||||
$ sudo pip install -U grpcio==0.11.0b1 |
||||
$ # Since this "hello, world" example uses protocol buffers: |
||||
$ sudo pip install -U protobuf==3.0.0a3 |
||||
$ # Clone the repository to get the example code: |
||||
$ git clone https://github.com/grpc/grpc |
||||
$ # Navigate to the "hello, world" Python example: |
||||
$ cd grpc/examples/python/helloworld |
||||
``` |
||||
|
||||
Try it! |
||||
------- |
||||
|
||||
- Run the server |
||||
|
||||
```sh |
||||
$ python2.7 greeter_server.py & |
||||
``` |
||||
|
||||
- Run the client |
||||
|
||||
```sh |
||||
$ python2.7 greeter_client.py |
||||
``` |
||||
|
||||
Tutorial |
||||
-------- |
||||
|
||||
You can find a more detailed tutorial in [gRPC Basics: Python][] |
||||
|
||||
[helloworld.proto]:../protos/helloworld.proto |
||||
[Install gRPC Python]:../../src/python#installation |
||||
[gRPC Basics: Python]:http://www.grpc.io/docs/tutorials/basic/python.html |
@ -1,113 +1 @@ |
||||
# gRPC Python Hello World |
||||
|
||||
This is a quick introduction with a simple example and installation instructions: for a more complete tutorial see [gRPC Basics: Python](../route_guide). |
||||
|
||||
### Install gRPC |
||||
Make sure you have built gRPC Python from source on your system. Follow the instructions here: |
||||
[https://github.com/grpc/grpc/blob/master/src/python/README.md](https://github.com/grpc/grpc/blob/master/src/python/README.md). |
||||
|
||||
This gives you a python virtual environment with installed gRPC Python |
||||
in GRPC_ROOT/python2.7_virtual_environment. GRPC_ROOT is the path to which you |
||||
have cloned the [gRPC git repo](https://github.com/grpc/grpc). |
||||
|
||||
### Get the source code |
||||
|
||||
The example code for our Hello World and our other examples live 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/python/helloworld |
||||
|
||||
```sh |
||||
$ cd examples/python/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. 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. |
||||
|
||||
``` |
||||
syntax = "proto3"; |
||||
|
||||
option java_package = "io.grpc.examples"; |
||||
|
||||
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 |
||||
$ ./run_codegen.sh |
||||
``` |
||||
Which internally invokes the proto-compiler as: |
||||
|
||||
```sh |
||||
$ protoc -I ../../protos --python_out=. --grpc_out=. --plugin=protoc-gen-grpc=`which grpc_python_plugin` ../../protos/helloworld.proto |
||||
``` |
||||
|
||||
### The client |
||||
|
||||
Client-side code can be found in [greeter_client.py](greeter_client.py). |
||||
|
||||
You can run the client using: |
||||
|
||||
```sh |
||||
$ ./run_client.sh |
||||
``` |
||||
|
||||
|
||||
### The server |
||||
|
||||
Server side code can be found in [greeter_server.py](greeter_server.py). |
||||
|
||||
You can run the server using: |
||||
|
||||
```sh |
||||
$ ./run_server.sh |
||||
``` |
||||
[This code's documentation lives on the grpc.io site.](http://www.grpc.io/docs) |
||||
|
@ -0,0 +1,202 @@ |
||||
# Generated by the protocol buffer compiler. DO NOT EDIT! |
||||
# source: helloworld.proto |
||||
|
||||
from google.protobuf import descriptor as _descriptor |
||||
from google.protobuf import message as _message |
||||
from google.protobuf import reflection as _reflection |
||||
from google.protobuf import symbol_database as _symbol_database |
||||
from google.protobuf import descriptor_pb2 |
||||
# @@protoc_insertion_point(imports) |
||||
|
||||
_sym_db = _symbol_database.Default() |
||||
|
||||
|
||||
|
||||
|
||||
DESCRIPTOR = _descriptor.FileDescriptor( |
||||
name='helloworld.proto', |
||||
package='helloworld', |
||||
syntax='proto3', |
||||
serialized_pb=b'\n\x10helloworld.proto\x12\nhelloworld\"\x1c\n\x0cHelloRequest\x12\x0c\n\x04name\x18\x01 \x01(\t\"\x1d\n\nHelloReply\x12\x0f\n\x07message\x18\x01 \x01(\t2I\n\x07Greeter\x12>\n\x08SayHello\x12\x18.helloworld.HelloRequest\x1a\x16.helloworld.HelloReply\"\x00\x42\x18\n\x10io.grpc.examples\xa2\x02\x03HLWb\x06proto3' |
||||
) |
||||
_sym_db.RegisterFileDescriptor(DESCRIPTOR) |
||||
|
||||
|
||||
|
||||
|
||||
_HELLOREQUEST = _descriptor.Descriptor( |
||||
name='HelloRequest', |
||||
full_name='helloworld.HelloRequest', |
||||
filename=None, |
||||
file=DESCRIPTOR, |
||||
containing_type=None, |
||||
fields=[ |
||||
_descriptor.FieldDescriptor( |
||||
name='name', full_name='helloworld.HelloRequest.name', index=0, |
||||
number=1, type=9, cpp_type=9, label=1, |
||||
has_default_value=False, default_value=b"".decode('utf-8'), |
||||
message_type=None, enum_type=None, containing_type=None, |
||||
is_extension=False, extension_scope=None, |
||||
options=None), |
||||
], |
||||
extensions=[ |
||||
], |
||||
nested_types=[], |
||||
enum_types=[ |
||||
], |
||||
options=None, |
||||
is_extendable=False, |
||||
syntax='proto3', |
||||
extension_ranges=[], |
||||
oneofs=[ |
||||
], |
||||
serialized_start=32, |
||||
serialized_end=60, |
||||
) |
||||
|
||||
|
||||
_HELLOREPLY = _descriptor.Descriptor( |
||||
name='HelloReply', |
||||
full_name='helloworld.HelloReply', |
||||
filename=None, |
||||
file=DESCRIPTOR, |
||||
containing_type=None, |
||||
fields=[ |
||||
_descriptor.FieldDescriptor( |
||||
name='message', full_name='helloworld.HelloReply.message', index=0, |
||||
number=1, type=9, cpp_type=9, label=1, |
||||
has_default_value=False, default_value=b"".decode('utf-8'), |
||||
message_type=None, enum_type=None, containing_type=None, |
||||
is_extension=False, extension_scope=None, |
||||
options=None), |
||||
], |
||||
extensions=[ |
||||
], |
||||
nested_types=[], |
||||
enum_types=[ |
||||
], |
||||
options=None, |
||||
is_extendable=False, |
||||
syntax='proto3', |
||||
extension_ranges=[], |
||||
oneofs=[ |
||||
], |
||||
serialized_start=62, |
||||
serialized_end=91, |
||||
) |
||||
|
||||
DESCRIPTOR.message_types_by_name['HelloRequest'] = _HELLOREQUEST |
||||
DESCRIPTOR.message_types_by_name['HelloReply'] = _HELLOREPLY |
||||
|
||||
HelloRequest = _reflection.GeneratedProtocolMessageType('HelloRequest', (_message.Message,), dict( |
||||
DESCRIPTOR = _HELLOREQUEST, |
||||
__module__ = 'helloworld_pb2' |
||||
# @@protoc_insertion_point(class_scope:helloworld.HelloRequest) |
||||
)) |
||||
_sym_db.RegisterMessage(HelloRequest) |
||||
|
||||
HelloReply = _reflection.GeneratedProtocolMessageType('HelloReply', (_message.Message,), dict( |
||||
DESCRIPTOR = _HELLOREPLY, |
||||
__module__ = 'helloworld_pb2' |
||||
# @@protoc_insertion_point(class_scope:helloworld.HelloReply) |
||||
)) |
||||
_sym_db.RegisterMessage(HelloReply) |
||||
|
||||
|
||||
DESCRIPTOR.has_options = True |
||||
DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), b'\n\020io.grpc.examples\242\002\003HLW') |
||||
import abc |
||||
from grpc.beta import implementations as beta_implementations |
||||
from grpc.early_adopter import implementations as early_adopter_implementations |
||||
from grpc.framework.alpha import utilities as alpha_utilities |
||||
from grpc.framework.common import cardinality |
||||
from grpc.framework.interfaces.face import utilities as face_utilities |
||||
class EarlyAdopterGreeterServicer(object): |
||||
"""<fill me in later!>""" |
||||
__metaclass__ = abc.ABCMeta |
||||
@abc.abstractmethod |
||||
def SayHello(self, request, context): |
||||
raise NotImplementedError() |
||||
class EarlyAdopterGreeterServer(object): |
||||
"""<fill me in later!>""" |
||||
__metaclass__ = abc.ABCMeta |
||||
@abc.abstractmethod |
||||
def start(self): |
||||
raise NotImplementedError() |
||||
@abc.abstractmethod |
||||
def stop(self): |
||||
raise NotImplementedError() |
||||
class EarlyAdopterGreeterStub(object): |
||||
"""<fill me in later!>""" |
||||
__metaclass__ = abc.ABCMeta |
||||
@abc.abstractmethod |
||||
def SayHello(self, request): |
||||
raise NotImplementedError() |
||||
SayHello.async = None |
||||
def early_adopter_create_Greeter_server(servicer, port, private_key=None, certificate_chain=None): |
||||
import helloworld_pb2 |
||||
import helloworld_pb2 |
||||
method_service_descriptions = { |
||||
"SayHello": alpha_utilities.unary_unary_service_description( |
||||
servicer.SayHello, |
||||
helloworld_pb2.HelloRequest.FromString, |
||||
helloworld_pb2.HelloReply.SerializeToString, |
||||
), |
||||
} |
||||
return early_adopter_implementations.server("helloworld.Greeter", method_service_descriptions, port, private_key=private_key, certificate_chain=certificate_chain) |
||||
def early_adopter_create_Greeter_stub(host, port, metadata_transformer=None, secure=False, root_certificates=None, private_key=None, certificate_chain=None, server_host_override=None): |
||||
import helloworld_pb2 |
||||
import helloworld_pb2 |
||||
method_invocation_descriptions = { |
||||
"SayHello": alpha_utilities.unary_unary_invocation_description( |
||||
helloworld_pb2.HelloRequest.SerializeToString, |
||||
helloworld_pb2.HelloReply.FromString, |
||||
), |
||||
} |
||||
return early_adopter_implementations.stub("helloworld.Greeter", method_invocation_descriptions, host, port, metadata_transformer=metadata_transformer, secure=secure, root_certificates=root_certificates, private_key=private_key, certificate_chain=certificate_chain, server_host_override=server_host_override) |
||||
|
||||
class BetaGreeterServicer(object): |
||||
"""<fill me in later!>""" |
||||
__metaclass__ = abc.ABCMeta |
||||
@abc.abstractmethod |
||||
def SayHello(self, request, context): |
||||
raise NotImplementedError() |
||||
|
||||
class BetaGreeterStub(object): |
||||
"""The interface to which stubs will conform.""" |
||||
__metaclass__ = abc.ABCMeta |
||||
@abc.abstractmethod |
||||
def SayHello(self, request, timeout): |
||||
raise NotImplementedError() |
||||
SayHello.future = None |
||||
|
||||
def beta_create_Greeter_server(servicer, pool=None, pool_size=None, default_timeout=None, maximum_timeout=None): |
||||
import helloworld_pb2 |
||||
import helloworld_pb2 |
||||
request_deserializers = { |
||||
('helloworld.Greeter', 'SayHello'): helloworld_pb2.HelloRequest.FromString, |
||||
} |
||||
response_serializers = { |
||||
('helloworld.Greeter', 'SayHello'): helloworld_pb2.HelloReply.SerializeToString, |
||||
} |
||||
method_implementations = { |
||||
('helloworld.Greeter', 'SayHello'): face_utilities.unary_unary_inline(servicer.SayHello), |
||||
} |
||||
server_options = beta_implementations.server_options(request_deserializers=request_deserializers, response_serializers=response_serializers, thread_pool=pool, thread_pool_size=pool_size, default_timeout=default_timeout, maximum_timeout=maximum_timeout) |
||||
return beta_implementations.server(method_implementations, options=server_options) |
||||
|
||||
def beta_create_Greeter_stub(channel, host=None, metadata_transformer=None, pool=None, pool_size=None): |
||||
import helloworld_pb2 |
||||
import helloworld_pb2 |
||||
request_serializers = { |
||||
('helloworld.Greeter', 'SayHello'): helloworld_pb2.HelloRequest.SerializeToString, |
||||
} |
||||
response_deserializers = { |
||||
('helloworld.Greeter', 'SayHello'): helloworld_pb2.HelloReply.FromString, |
||||
} |
||||
cardinalities = { |
||||
'SayHello': cardinality.Cardinality.UNARY_UNARY, |
||||
} |
||||
stub_options = beta_implementations.stub_options(host=host, metadata_transformer=metadata_transformer, request_serializers=request_serializers, response_deserializers=response_deserializers, thread_pool=pool, thread_pool_size=pool_size) |
||||
return beta_implementations.dynamic_stub(channel, 'helloworld.Greeter', cardinalities, options=stub_options) |
||||
# @@protoc_insertion_point(module_scope) |
@ -1,299 +1 @@ |
||||
#gRPC Basics: Python |
||||
|
||||
This tutorial provides a basic Python 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 Python 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 Python: more reference documentation is coming soon. |
||||
|
||||
|
||||
## Why use gRPC? |
||||
|
||||
This 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 you can define your 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, with all the complexity of communication between different languages and environments is handled for you by gRPC. You 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 this tutorial is in [examples/python/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/python/route_guide`: |
||||
```shell |
||||
$ cd examples/python/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 Python quick start guide](../helloworld). |
||||
|
||||
## Defining the service |
||||
|
||||
Your first step (as you'll know from [Getting started](https://github.com/grpc/grpc/tree/master/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`](../../protos/route_guide.proto). |
||||
|
||||
To define a service, you specify a named `service` in your .proto file: |
||||
|
||||
```protobuf |
||||
service RouteGuide { |
||||
// (Method definitions not shown) |
||||
} |
||||
``` |
||||
|
||||
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. |
||||
```protobuf |
||||
// Obtains the feature at a given position. |
||||
rpc GetFeature(Point) returns (Feature) {} |
||||
``` |
||||
|
||||
- A *response-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 the example, you specify a response-streaming method by placing the `stream` keyword before the *response* type. |
||||
```protobuf |
||||
// 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 *request-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 request-streaming method by placing the `stream` keyword before the *request* type. |
||||
```protobuf |
||||
// Accepts a stream of Points on a route being traversed, returning a |
||||
// RouteSummary when traversal is completed. |
||||
rpc RecordRoute(stream Point) returns (RouteSummary) {} |
||||
``` |
||||
|
||||
- A *bidirectionally-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. |
||||
```protobuf |
||||
// 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) {} |
||||
``` |
||||
|
||||
Your .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: |
||||
```protobuf |
||||
// 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 you need to generate the gRPC client and server interfaces from your .proto service definition. You do this using the protocol buffer compiler `protoc` with a special gRPC Python plugin. Make sure you've installed protoc and followed the gRPC Python plugin [installation instructions](https://github.com/grpc/grpc/blob/master/INSTALL) first): |
||||
|
||||
With `protoc` and the gRPC Python plugin installed, use the following command to generate the Python code: |
||||
|
||||
```shell |
||||
$ protoc -I ../../protos --python_out=. --grpc_out=. --plugin=protoc-gen-grpc=`which grpc_python_plugin` ../../protos/route_guide.proto |
||||
``` |
||||
|
||||
Note that as we've already provided a version of the generated code in the example repository, running this command regenerates the appropriate file rather than creates a new one. The generated code file is called `route_guide_pb2.py` and contains: |
||||
- classes for the messages defined in route_guide.proto |
||||
- abstract classes for the service defined in route_guide.proto |
||||
- `BetaRouteGuideServicer`, which defines the interface for implementations of the RouteGuide service |
||||
- `BetaRouteGuideStub`, which can be used by clients to invoke RouteGuide RPCs |
||||
- functions for application use |
||||
- `beta_create_RouteGuide_server`, which creates a gRPC server given a `BetaRouteGuideServicer` object |
||||
- `beta_create_RouteGuide_stub`, which can be used by clients to create a stub object |
||||
|
||||
<a name="server"></a> |
||||
## Creating the server |
||||
|
||||
First let's look at how you 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!). |
||||
|
||||
Creating and running a `RouteGuide` server breaks down into two work items: |
||||
- Implementing the servicer interface generated from our service definition with functions that perform the actual "work" of the service. |
||||
- Running a gRPC server to listen for requests from clients and transmit responses. |
||||
|
||||
You can find the example `RouteGuide` server in [route_guide_server.py](route_guide_server.py). |
||||
|
||||
### Implementing RouteGuide |
||||
|
||||
`route_guide_server.py` has a `RouteGuideServicer` class that implements the generated interface `route_guide_pb2.BetaRouteGuideServicer`: |
||||
|
||||
```python |
||||
# RouteGuideServicer provides an implementation of the methods of the RouteGuide service. |
||||
class RouteGuideServicer(route_guide_pb2.BetaRouteGuideServicer): |
||||
``` |
||||
|
||||
`RouteGuideServicer` implements all the `RouteGuide` service methods. |
||||
|
||||
#### Simple RPC |
||||
|
||||
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`. |
||||
|
||||
```python |
||||
def GetFeature(self, request, context): |
||||
feature = get_feature(self.db, request) |
||||
if feature is None: |
||||
return route_guide_pb2.Feature(name="", location=request) |
||||
else: |
||||
return feature |
||||
``` |
||||
|
||||
The method is passed a `route_guide_pb2.Point` request for the RPC, and a `ServicerContext` object that provides RPC-specific information such as timeout limits. It returns a `route_guide_pb2.Feature` response. |
||||
|
||||
#### Response-streaming RPC |
||||
|
||||
Now let's look at the next method. `ListFeatures` is a response-streaming RPC that sends multiple `Feature`s to the client. |
||||
|
||||
```python |
||||
def ListFeatures(self, request, context): |
||||
left = min(request.lo.longitude, request.hi.longitude) |
||||
right = max(request.lo.longitude, request.hi.longitude) |
||||
top = max(request.lo.latitude, request.hi.latitude) |
||||
bottom = min(request.lo.latitude, request.hi.latitude) |
||||
for feature in self.db: |
||||
if (feature.location.longitude >= left and |
||||
feature.location.longitude <= right and |
||||
feature.location.latitude >= bottom and |
||||
feature.location.latitude <= top): |
||||
yield feature |
||||
``` |
||||
|
||||
Here the request message is a `route_guide_pb2.Rectangle` within which the client wants to find `Feature`s. Instead of returning a single response the method yields zero or more responses. |
||||
|
||||
#### Request-streaming RPC |
||||
|
||||
The request-streaming method `RecordRoute` uses an [iterator](https://docs.python.org/2/library/stdtypes.html#iterator-types) of request values and returns a single response value. |
||||
|
||||
```python |
||||
def RecordRoute(self, request_iterator, context): |
||||
point_count = 0 |
||||
feature_count = 0 |
||||
distance = 0.0 |
||||
prev_point = None |
||||
|
||||
start_time = time.time() |
||||
for point in request_iterator: |
||||
point_count += 1 |
||||
if get_feature(self.db, point): |
||||
feature_count += 1 |
||||
if prev_point: |
||||
distance += get_distance(prev_point, point) |
||||
prev_point = point |
||||
|
||||
elapsed_time = time.time() - start_time |
||||
return route_guide_pb2.RouteSummary(point_count=point_count, |
||||
feature_count=feature_count, |
||||
distance=int(distance), |
||||
elapsed_time=int(elapsed_time)) |
||||
``` |
||||
|
||||
#### Bidirectional streaming RPC |
||||
|
||||
Lastly let's look at the bidirectionally-streaming method `RouteChat`. |
||||
|
||||
```python |
||||
def RouteChat(self, request_iterator, context): |
||||
prev_notes = [] |
||||
for new_note in request_iterator: |
||||
for prev_note in prev_notes: |
||||
if prev_note.location == new_note.location: |
||||
yield prev_note |
||||
prev_notes.append(new_note) |
||||
``` |
||||
|
||||
This method's semantics are a combination of those of the request-streaming method and the response-streaming method. It is passed an iterator of request values and is itself an iterator of response values. |
||||
|
||||
### Starting the server |
||||
|
||||
Once you have implemented all the `RouteGuide` methods, the next step is to start up a gRPC server so that clients can actually use your service: |
||||
|
||||
```python |
||||
def serve(): |
||||
server = route_guide_pb2.beta_create_RouteGuide_server(RouteGuideServicer()) |
||||
server.add_insecure_port('[::]:50051') |
||||
server.start() |
||||
``` |
||||
|
||||
Because `start()` does not block you may need to sleep-loop if there is nothing else for your code to do while serving. |
||||
|
||||
<a name="client"></a> |
||||
## Creating the client |
||||
|
||||
You can see the complete example client code in [route_guide_client.py](route_guide_client.py). |
||||
|
||||
### Creating a stub |
||||
|
||||
To call service methods, we first need to create a *stub*. |
||||
|
||||
We use the `beta_create_RouteGuide_stub` function of the `route_guide_pb2` module, generated from our .proto. |
||||
|
||||
```python |
||||
channel = implementations.insecure_channel('localhost', 50051) |
||||
stub = beta_create_RouteGuide_stub(channel) |
||||
``` |
||||
|
||||
The returned object implements all the methods defined by the `BetaRouteGuideStub` interface. |
||||
|
||||
### Calling service methods |
||||
|
||||
For RPC methods that return a single response ("response-unary" methods), gRPC Python supports both synchronous (blocking) and asynchronous (non-blocking) control flow semantics. For response-streaming RPC methods, calls immediately return an iterator of response values. Calls to that iterator's `next()` method block until the response to be yielded from the iterator becomes available. |
||||
|
||||
#### Simple RPC |
||||
|
||||
A synchronous call to the simple RPC `GetFeature` is nearly as straightforward as calling a local method. The RPC call waits for the server to respond, and will either return a response or raise an exception: |
||||
|
||||
```python |
||||
feature = stub.GetFeature(point, timeout_in_seconds) |
||||
``` |
||||
|
||||
An asynchronous call to `GetFeature` is similar, but like calling a local method asynchronously in a thread pool: |
||||
|
||||
```python |
||||
feature_future = stub.GetFeature.future(point, timeout_in_seconds) |
||||
feature = feature_future.result() |
||||
``` |
||||
|
||||
#### Response-streaming RPC |
||||
|
||||
Calling the response-streaming `ListFeatures` is similar to working with sequence types: |
||||
|
||||
```python |
||||
for feature in stub.ListFeatures(rectangle, timeout_in_seconds): |
||||
``` |
||||
|
||||
#### Request-streaming RPC |
||||
|
||||
Calling the request-streaming `RecordRoute` is similar to passing a sequence to a local method. Like the simple RPC above that also returns a single response, it can be called synchronously or asynchronously: |
||||
|
||||
```python |
||||
route_summary = stub.RecordRoute(point_sequence, timeout_in_seconds) |
||||
``` |
||||
|
||||
```python |
||||
route_summary_future = stub.RecordRoute.future(point_sequence, timeout_in_seconds) |
||||
route_summary = route_summary_future.result() |
||||
``` |
||||
|
||||
#### Bidirectional streaming RPC |
||||
|
||||
Calling the bidirectionally-streaming `RouteChat` has (as is the case on the service-side) a combination of the request-streaming and response-streaming semantics: |
||||
|
||||
```python |
||||
for received_route_note in stub.RouteChat(sent_routes, timeout_in_seconds): |
||||
``` |
||||
|
||||
## Try it out! |
||||
|
||||
Run the server, which will listen on port 50051: |
||||
|
||||
```shell |
||||
$ python route_guide_server.py |
||||
``` |
||||
|
||||
Run the client (in a different terminal): |
||||
|
||||
```shell |
||||
$ python route_guide_client.py |
||||
``` |
||||
[This code's documentation lives on the grpc.io site.](http://www.grpc.io/docs/tutorials/basic/python.html) |
||||
|
@ -1,285 +1,6 @@ |
||||
#gRPC Basics: Ruby |
||||
#gRPC Basics: Ruby sample code |
||||
|
||||
This tutorial provides a basic Ruby 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 Ruby 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 Ruby: 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/ruby/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/ruby/route_guide`: |
||||
```shell |
||||
$ cd examples/ruby/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 Ruby quick start guide](..). |
||||
|
||||
|
||||
## Defining the service |
||||
|
||||
Our first step (as you'll know from [Getting started](https://github.com/grpc/grpc/tree/master/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`](../../route_guide.proto). |
||||
|
||||
To define a service, you specify a named `service` in your .proto file: |
||||
|
||||
```protobuf |
||||
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. |
||||
```protobuf |
||||
// 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. |
||||
```protobuf |
||||
// 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 server-side streaming method by placing the `stream` keyword before the *request* type. |
||||
```protobuf |
||||
// 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. |
||||
```protobuf |
||||
// 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: |
||||
```protobuf |
||||
// 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 Ruby plugin. |
||||
|
||||
If you want to run this yourself, make sure you've installed protoc and followed the gRPC Ruby plugin [installation instructions](https://github.com/grpc/grpc/blob/master/INSTALL) first): |
||||
|
||||
Once that's done, the following command can be used to generate the ruby code. |
||||
|
||||
```shell |
||||
$ protoc -I ../../protos --ruby_out=lib --grpc_out=lib --plugin=protoc-gen-grpc=`which grpc_ruby_plugin` ../../protos/route_guide.proto |
||||
``` |
||||
|
||||
Running this command regenerates the following files in the lib directory: |
||||
- `lib/route_guide.pb` defines a module `Examples::RouteGuide` |
||||
- This contain all the protocol buffer code to populate, serialize, and retrieve our request and response message types |
||||
- `lib/route_guide_services.pb`, extends `Examples::RouteGuide` with stub and service classes |
||||
- a class `Service` for use as a base class when defining RouteGuide service implementations |
||||
- a class `Stub` that can be used to access remote RouteGuide instances |
||||
|
||||
|
||||
<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 [route_guide_server.rb](route_guide_server.rb). Let's take a closer look at how it works. |
||||
|
||||
### Implementing RouteGuide |
||||
|
||||
As you can see, our server has a `ServerImpl` class that extends the generated `RouteGuide::Service`: |
||||
|
||||
```ruby |
||||
# ServerImpl provides an implementation of the RouteGuide service. |
||||
class ServerImpl < RouteGuide::Service |
||||
``` |
||||
|
||||
`ServerImpl` 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`. |
||||
|
||||
```ruby |
||||
def get_feature(point, _call) |
||||
name = @feature_db[{ |
||||
'longitude' => point.longitude, |
||||
'latitude' => point.latitude }] || '' |
||||
Feature.new(location: point, name: name) |
||||
end |
||||
``` |
||||
|
||||
The method is passed a _call for the RPC, the client's `Point` protocol buffer request, and returns a `Feature` protocol buffer. In the method we create the `Feature` with the appropriate information, and then `return` it. |
||||
|
||||
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. |
||||
|
||||
```ruby |
||||
# in ServerImpl |
||||
|
||||
def list_features(rectangle, _call) |
||||
RectangleEnum.new(@feature_db, rectangle).each |
||||
end |
||||
``` |
||||
|
||||
As you can see, here the request object is a `Rectangle` in which our client wants to find `Feature`s, but instead of returning a simple response we need to return an [Enumerator](http://ruby-doc.org//core-2.2.0/Enumerator.html) that yields the responses. In the method, we use a helper class `RectangleEnum`, to act as an Enumerator implementation. |
||||
|
||||
Similarly, the client-side streaming method `record_route` uses an [Enumerable](http://ruby-doc.org//core-2.2.0/Enumerable.html), but here it's obtained from the call object, which we've ignored in the earlier examples. `call.each_remote_read` yields each message sent by the client in turn. |
||||
|
||||
```ruby |
||||
call.each_remote_read do |point| |
||||
... |
||||
end |
||||
``` |
||||
Finally, let's look at our bidirectional streaming RPC `route_chat`. |
||||
|
||||
```ruby |
||||
def route_chat(notes) |
||||
q = EnumeratorQueue.new(self) |
||||
t = Thread.new do |
||||
begin |
||||
notes.each do |n| |
||||
... |
||||
end |
||||
end |
||||
q = EnumeratorQueue.new(self) |
||||
... |
||||
return q.each_item |
||||
end |
||||
``` |
||||
|
||||
Here the method receives an [Enumerable](http://ruby-doc.org//core-2.2.0/Enumerable.html), but also returns an [Enumerator](http://ruby-doc.org//core-2.2.0/Enumerator.html) that yields the responses. The implementation demonstrates how to set these up so that the requests and responses can be handled concurrently. 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: |
||||
|
||||
```ruby |
||||
s = GRPC::RpcServer.new |
||||
s.add_http2_port(port) |
||||
logger.info("... running insecurely on #{port}") |
||||
s.handle(ServerImpl.new(feature_db)) |
||||
s.run |
||||
``` |
||||
As you can see, we build and start our server using a `GRPC::RpcServer`. To do this, we: |
||||
|
||||
1. Create an instance of our service implementation class `ServerImpl`. |
||||
2. Specify the address and port we want to use to listen for client requests using the builder's `add_http2_port` method. |
||||
3. Register our service implementation with the `GRPC::RpcServer`. |
||||
4. Call `run` on the`GRPC::RpcServer` to create and start an RPC server for our service. |
||||
|
||||
<a name="client"></a> |
||||
## Creating the client |
||||
|
||||
In this section, we'll look at creating a Ruby client for our `RouteGuide` service. You can see our complete example client code in [route_guide_client.rb](route_guide_client.rb). |
||||
|
||||
### Creating a stub |
||||
|
||||
To call service methods, we first need to create a *stub*. |
||||
|
||||
We use the `Stub` class of the `RouteGuide` module generated from our .proto. |
||||
|
||||
```ruby |
||||
stub = RouteGuide::Stub.new('localhost:50051') |
||||
``` |
||||
|
||||
### Calling service methods |
||||
|
||||
Now let's look at how we call our service methods. Note that the gRPC Ruby only provides *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. |
||||
|
||||
```ruby |
||||
GET_FEATURE_POINTS = [ |
||||
Point.new(latitude: 409_146_138, longitude: -746_188_906), |
||||
Point.new(latitude: 0, longitude: 0) |
||||
] |
||||
.. |
||||
GET_FEATURE_POINTS.each do |pt| |
||||
resp = stub.get_feature(pt) |
||||
... |
||||
p "- found '#{resp.name}' at #{pt.inspect}" |
||||
end |
||||
``` |
||||
|
||||
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. 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. |
||||
|
||||
|
||||
#### 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 `list_features`, which returns an `Enumerable` of `Features` |
||||
|
||||
```ruby |
||||
resps = stub.list_features(LIST_FEATURES_RECT) |
||||
resps.each do |r| |
||||
p "- found '#{r.name}' at #{r.location.inspect}" |
||||
end |
||||
``` |
||||
|
||||
The client-side streaming method `record_route` is similar, except there we pass the server an `Enumerable`. |
||||
|
||||
```ruby |
||||
... |
||||
reqs = RandomRoute.new(features, points_on_route) |
||||
resp = stub.record_route(reqs.each, deadline) |
||||
... |
||||
``` |
||||
|
||||
Finally, let's look at our bidirectional streaming RPC `route_chat`. In this case, we pass `Enumerable` to the method and get back an `Enumerable`. |
||||
|
||||
```ruby |
||||
resps = stub.route_chat(ROUTE_CHAT_NOTES) |
||||
resps.each { |r| p "received #{r.inspect}" } |
||||
``` |
||||
|
||||
Although it's not shown well by this example, each enumerable is independent of the other - 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 |
||||
$ # from examples/ruby |
||||
$ gem install bundler && bundle install |
||||
``` |
||||
Run the server, which will listen on port 50051: |
||||
```shell |
||||
$ # from examples/ruby |
||||
$ bundle exec route_guide/route_guide_server.rb ../node/route_guide/route_guide_db.json & |
||||
``` |
||||
Run the client (in a different terminal): |
||||
```shell |
||||
$ # from examples/ruby |
||||
$ bundle exec route_guide/route_guide_client.rb ../node/route_guide/route_guide_db.json & |
||||
``` |
||||
The files in this folder are the samples used in [gRPC Basics: Ruby][], |
||||
a detailed tutorial for using gRPC in Ruby. |
||||
|
||||
[gRPC Basics: Ruby]:http://www.grpc.io/docs/tutorials/basic/ruby.html |
||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in new issue