mirror of https://github.com/grpc/grpc.git
commit
cc545461c0
247 changed files with 10233 additions and 3050 deletions
File diff suppressed because it is too large
Load Diff
@ -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,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 |
||||
|
@ -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 |
||||
|
@ -0,0 +1,65 @@ |
||||
/*
|
||||
* |
||||
* Copyright 2015, Google Inc. |
||||
* All rights reserved. |
||||
* |
||||
* Redistribution and use in source and binary forms, with or without |
||||
* modification, are permitted provided that the following conditions are |
||||
* met: |
||||
* |
||||
* * Redistributions of source code must retain the above copyright |
||||
* notice, this list of conditions and the following disclaimer. |
||||
* * Redistributions in binary form must reproduce the above |
||||
* copyright notice, this list of conditions and the following disclaimer |
||||
* in the documentation and/or other materials provided with the |
||||
* distribution. |
||||
* * Neither the name of Google Inc. nor the names of its |
||||
* contributors may be used to endorse or promote products derived from |
||||
* this software without specific prior written permission. |
||||
* |
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
||||
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT |
||||
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
||||
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT |
||||
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
||||
* |
||||
*/ |
||||
|
||||
#ifndef GRPC_INTERNAL_CORE_SURFACE_API_TRACE_H |
||||
#define GRPC_INTERNAL_CORE_SURFACE_API_TRACE_H |
||||
|
||||
#include "src/core/debug/trace.h" |
||||
#include <grpc/support/log.h> |
||||
|
||||
extern int grpc_api_trace; |
||||
|
||||
/* Provide unwrapping macros because we're in C89 and variadic macros weren't
|
||||
introduced until C99... */ |
||||
#define GRPC_API_TRACE_UNWRAP0() |
||||
#define GRPC_API_TRACE_UNWRAP1(a) , a |
||||
#define GRPC_API_TRACE_UNWRAP2(a, b) , a, b |
||||
#define GRPC_API_TRACE_UNWRAP3(a, b, c) , a, b, c |
||||
#define GRPC_API_TRACE_UNWRAP4(a, b, c, d) , a, b, c, d |
||||
#define GRPC_API_TRACE_UNWRAP5(a, b, c, d, e) , a, b, c, d, e |
||||
#define GRPC_API_TRACE_UNWRAP6(a, b, c, d, e, f) , a, b, c, d, e, f |
||||
#define GRPC_API_TRACE_UNWRAP7(a, b, c, d, e, f, g) , a, b, c, d, e, f, g |
||||
#define GRPC_API_TRACE_UNWRAP8(a, b, c, d, e, f, g, h) , a, b, c, d, e, f, g, h |
||||
#define GRPC_API_TRACE_UNWRAP9(a, b, c, d, e, f, g, h, i) \ |
||||
, a, b, c, d, e, f, g, h, i |
||||
#define GRPC_API_TRACE_UNWRAP10(a, b, c, d, e, f, g, h, i, j) \ |
||||
, a, b, c, d, e, f, g, h, i, j |
||||
|
||||
/* Due to the limitations of C89's preprocessor, the arity of the var-arg list
|
||||
'nargs' must be specified. */ |
||||
#define GRPC_API_TRACE(fmt, nargs, args) \ |
||||
if (grpc_api_trace) { \
|
||||
gpr_log(GPR_INFO, fmt GRPC_API_TRACE_UNWRAP##nargs args); \
|
||||
} |
||||
|
||||
#endif /* GRPC_INTERNAL_CORE_SURFACE_API_TRACE_H */ |
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in new issue