Documentation

Getting started

Welcome to the developer documentation for gRPC, a language-neutral, platform-neutral, open source, remote procedure call (RPC) system initially developed at Google.

This document introduces you to gRPC with a quick overview and a simple Hello World example. You’ll find more tutorials and reference docs in this site - more documentation is coming soon!

Quick start

To get up and running with gRPC straight away, see the quick start for your chosen language, which provides links to installation instructions, quick instructions for building the example used in this guide, and more:

You can find out about the gRPC source code repositories in grpc. Most of our example code lives in the examples directory.

What is gRPC?

In gRPC a client application can directly call methods on a server application on a different machine as if it was a local object, making it easier for you to create distributed applications and services. As in many RPC systems, gRPC is based around the idea of defining a service, specifying the methods that can be called remotely with their parameters and return types. On the server side, the server implements this interface and runs a gRPC server to handle client calls. On the client side, the client has a stub (referred to as just client in some languages) that provides the same methods as the server.

gRPC diagram

gRPC clients and servers can run and talk to each other in a variety of environments - from servers inside Google to your own desktop - and can be written in any of gRPC’s supported languages. So, for example, you can easily create a gRPC server in Java with clients in Go, Python, or Ruby. In addition, the latest Google APIs will have gRPC versions of their interfaces, letting you easily build Google functionality into your applications.

Working with protocol buffers

By default gRPC uses protocol buffers, Google’s mature open source mechanism for serializing structured data (although it can be used with other data formats such as JSON). As you’ll see in our example below, you define gRPC services using proto files, with method parameters and return types specified as protocol buffer message types. You can find out lots more about protocol buffers in the Protocol Buffers documentation.

Protocol buffer versions

While protocol buffers have been available for open source users for some time, our examples use a new flavor of protocol buffers called proto3, which has a slightly simplified syntax, some useful new features, and supports lots more languages. This is currently available as a beta release in Java, C++, Python, Objective-C, and C#, with an alpha release for JavaNano (Android Java), Ruby, and JavaScript from the protocol buffers Github repo, as well as a Go language generator from the golang/protobuf Github repo, with more languages in development. You can find out more in the proto3 language guide and the reference documentation for each language (where available), and see the major differences from the current default version in the release notes. Even more proto3 documentation is coming soon.

In general, while you can use proto2 (the current default protocol buffers version), we recommend that you use proto3 with gRPC as it lets you use the full range of gRPC-supported languages, as well as avoiding compatibility issues with proto2 clients talking to proto3 servers and vice versa.

Hello gRPC!

Now that you know a bit more about gRPC, the easiest way to see how it works is to look at a simple example. Our Hello World walks you through the construction of a simple gRPC client-server application, showing you how to:

  • Create a protocol buffers schema that defines a simple RPC service with a single Hello World method.
  • Create a server that implements this interface in your favourite language (where available).
  • Create a client in your favourite language (or any other one you like!) that accesses your server.

The complete code for the examples is available in the examples directory in our GitHub repositories. We use the Git versioning system for source code management: however, you don’t need to know anything about Git to follow along other than how to install and run a few git commands.

Note that server code for our example isn’t available in all gRPC languages, as gRPC PHP and Objective-C only support creating clients.

This is an introductory example rather than a comprehensive tutorial for any particular language. You can find more in-depth tutorials in this site, and reference documentation for all gRPC languages is coming soon.

Setup

This section explains how to set up your local machine to work with the example code. If you just want to read the examples, you can go straight to the next step.

Install Git

You can download and install Git from http://git-scm.com/download. Once installed you should have access to the git command line tool. The main commands that you will need to use are:

  • git clone ... : clone a remote repository onto your local machine
  • git checkout ... : check out a particular branch or a tagged version of the code to hack on

Get the source code

The example code for our Java example lives in the grpc-java GitHub repository. Clone this repository to your local machine by running the following command:
  git clone https://github.com/grpc/grpc-java.git
  
Change your current directory to grpc-java/examples.
  cd grpc-java/examples
  
The example code for this lives in the examples directory in our GitHub repositories. Clone this repository to your local machine by running the following command:
  $ git clone -b $(curl -L http://grpc.io/release) https://github.com/grpc/grpc
  
Change your current directory to examples/cpp/helloworld
  $ cd examples/cpp/helloworld/
  
The example code for this lives in the examples directory in our GitHub repositories. Clone this repository to your local machine by running the following command:
  $ git clone -b $(curl -L http://grpc.io/release) https://github.com/grpc/grpc
  
Change your current directory to examples/python/helloworld
  $ cd examples/python/helloworld/
  
Get the example:
  $ go get -u github.com/grpc/grpc-go/examples/helloworld/greeter_client
  $ go get -u github.com/grpc/grpc-go/examples/helloworld/greeter_server
  
Change your current directory to examples/helloworld
The example code for this lives in the examples directory in our GitHub repositories. Clone this repository to your local machine by running the following command:</p>
  $ git clone -b $(curl -L http://grpc.io/release) https://github.com/grpc/grpc
  
Change your current directory to examples/ruby. Then use bundler to install the example package's dependencies:</p>
  $ gem install bundler # if you don't already have bundler available
  $ bundle install
  

The example code for this lives in the examples directory in our GitHub repositories. Clone this repository to your local machine by running the following command:

$ git clone -b $(curl -L http://grpc.io/release) https://github.com/grpc/grpc

Change your current directory to examples/node, then install this package's dependencies:

$ cd examples/node
$ npm install

The example code for this lives in the examples directory in our GitHub repositories. Clone this repository to your local machine by running the following command:

$ git clone -b $(curl -L http://grpc.io/release) https://github.com/grpc/grpc

Open Greeter.sln from Visual Studio (or Monodevelop on Linux).

The example code for this lives in the examples directory in our GitHub repositories. Clone this repository to your local machine by running the following commands:

$ git clone -b $(curl -L http://grpc.io/release) https://github.com/grpc/grpc
$ cd grpc
$ git submodule update --init

Change your current directory to examples/objective-c/helloworld.

The example code for this lives in the examples in our GitHub repositories. Clone this repository to your local machine by running the following command:

$ git clone -b $(curl -L http://grpc.io/release) https://github.com/grpc/grpc

Change your current directory to examples/php.

While most of our Hello World examples use the same .proto file, the PHP example has its own copy of helloworld.proto because it currently depends on some proto2 syntax. There is no proto3 support for PHP yet.

Install gRPC

To run the example (and our tutorial examples, and any gRPC projects you create yourself), you need to install the gRPC runtime for your chosen language. In addition, if you want to try generating gRPC code, depending on your chosen language you may need to install the protocol buffers compiler with the appropriate gRPC plugin. We intend to further simplify this process in future releases.

To install the gRPC runtime for your chosen language:

This example is also part of Java gRPC itself's build, so running it is a little different to creating and running a regular project. To install and build it follow the instructions in the Quickstart.

To install the runtime for your own projects, add the following to your build files:

Gradle:

compile 'io.grpc:grpc-all:0.15.0'

Maven:

<dependency>
  <groupId>io.grpc</groupId>
  <artifactId>grpc-all</artifactId>
  <version>0.15.0</version>
</dependency>
Currently you need to build the C++ runtime from source. You can find the instructions in the gRPC Github repository.
On Mac, Linux, and Windows, run:
pip install grpcio
On Mac, Linux, and Windows, run:
go get google.golang.org/grpc
On Mac, Linux, and Windows, run:
gem install grpc
On Mac, Linux, and Windows, run:
npm install grpc
On Mac, Linux, and Windows, install the gRPC NuGet package from your IDE (Visual Studio, Monodevelop, Xamarin Studio).
If you're using Cocoapods on Mac, once you get the example source the runtime source code is fetched automatically from Github and integrated into your project. (It's also possible to install on Windows or Linux, but you need to download the source code and integrate it manually into your project.)
On Mac and Linux, run:
pecl install grpc-beta

For more detailed installation instructions - for instance, if you want to build gRPC from source - see the gRPC source repositories at grpc (instructions are in each language’s subfolder), grpc-java, and grpc-go.

To install protocol buffers support (the protocol buffer compiler and the protocol buffers runtime) with gRPC for your chosen language:

Again, the example is also part of Java gRPC itself's build, and includes pre-generated gRPC code - we recommend that you use this when working through this example. See the README for instructions on how to install the protocol buffer compiler for your own projects.
If you build and install gRPC from source, the Makefile will automatically install protoc as well (if you don't already have it installed). Installing gRPC also gets you the gRPC C++ plugin for protoc.
On Mac, Linux, and Windows, run:
  pip install grpcio-tools
  
First install protoc from its Github repository. Then get the Go protoc plugin:
  $ go get -a github.com/golang/protobuf/protoc-gen-go
  
On Mac, Linux, and Windows, run:
  gem install grpc-tools
  
The Node.js gRPC library can either dynamically generate the necessary gRPC code at runtime or you can use the protocol buffer code generated by protoc. In our example we're going to use dynamic code generation, so if you want to follow along you don't need to have the protocol buffer compiler installed. If you do want to use statically generated code, you can install the compiler by running:
  npm install grpc-tools
  
Install the Google.Protobuf and Grpc.Tools NuGet packages from your IDE (Visual Studio, Xamarin Studio or Monodevelop).
Follow the instructions in gRPC for Objective C to install protoc and the appropriate plugin. Instructions are provided for installation with and without Homebrew.
First install protoc from its Github repository. Then install the third-party protoc-gen-php plugin.

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 above, gRPC does this using protocol buffers. 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, defined using protocol buffers IDL in helloworld.proto. The Greeter service has one method, SayHello, 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 - you can find out about other types in the tutorial for your chosen language.

syntax = "proto3";

option java_package = "io.grpc.examples";

package helloworld;

// The greeter 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;
}

As you can see, a gRPC method can accept only a single protocol buffer message type as its request (in this case, the HelloRequest message type defined in our .proto), and return only a single protocol buffer type as its response - this is the case for all gRPC methods. However, this doesn’t limit you in what kind of data you can pass between gRPC clients and servers in the same RPC - to add more arguments, or values to return, you just add more fields to the appropriate protocol buffer request or response type.

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 - you can generate gRPC code in any gRPC-supported language, although PHP and Objective-C only support creating clients. The generated code contains both client-side code for clients to call into and an abstract interface for servers to implement, both with the method defined in our Greeter service.

(If you didn’t install the gRPC plugins and protoc on your system and are just reading along with the example, you can skip this step and move onto the next one where we examine the generated code.)

As we mentioned in our installation section, the build system for this example is also part of Java gRPC itself's build — for simplicity we recommend using our pre-generated code for the example. You can refer to the README for how to generate code from your own .proto files.

Pre-generated code for the examples is available in src/generated/main. The following classes contain all the generated code we need to create our example:

  • HelloRequest.java, HelloResponse.java, and others which have all the protocol buffer code to populate, serialize, and retrieve our HelloRequest and HelloReply message types
  • GreeterGrpc.java, which contains (along with some other useful code):
    • an abstract base class for Greeter servers to implement
            public static abstract class GreeterImplBase {
              ...
              public void sayHello(Helloworld.HelloRequest request,
                  StreamObserver<Helloworld.HelloReply> responseObserver) {
                ...
              }
            }
            
    • stub classes that clients can use to talk to a Greeter server.
            public static class GreeterStub extends AbstractStub<GreeterStub> {
              ...
            }
            

To generate the client and server side interfaces, run:

  $ make helloworld.grpc.pb.cc helloworld.pb.cc
  

Which internally invokes the protocol buffer compiler as:

  $ protoc -I ../../protos/ --grpc_out=. --plugin=protoc-gen-grpc=grpc_cpp_plugin ../../protos/helloworld.proto
  $ protoc -I ../../protos/ --cpp_out=. ../../protos/helloworld.proto
  

This generates:

  • helloworld.pb.h, which declares classes for populating, serializing, and retrieving our HelloRequest and HelloResponse message types, and its implementation helloworld.pb.cc.
  • helloworld.grpc.pb.h, which declares our generated service classes, and its implementation helloworld.grpc.pb.cc.
To generate the client and server side interfaces:
  $ ./run_codegen.sh
  
Which internally invokes the protocol buffer compiler as:
$ python -m grpc.tools.protoc -I../../protos --python_out=. --grpc_python_out=. ../../protos/helloworld.proto
This generates helloworld_pb2.py, which contains our generated client and server classes, as well as classes for populating, serializing, and retrieving our HelloRequest and HelloResponse message types.
To generate the client and server side interfaces, run the protocol buffer compiler:
  protoc -I ../protos ../protos/helloworld.proto --go_out=plugins=grpc:helloworld
  
This generates `helloworld.pb.go`, which contains our generated client and server code, as well as code for populating, serializing, and retrieving our `HelloRequest` and `HelloResponse` message types.
To generate the client and server side interfaces, run the protocol buffer compiler:
  protoc -I ../protos --ruby_out=lib --grpc_out=lib --plugin=protoc-gen-grpc=`which grpc_ruby_plugin` ../protos/helloworld.proto
  
This generates the following files in the lib directory:
  • lib/helloworld.rb defines a module Helloworld, which provides all the protocol buffer code to populate, serialize, and retrieve our request and response message types.
  • lib/helloworld_services.rb extends the Helloworld module with our generated client and server classes.
The Node.js library dynamically generates service descriptors and client stub definitions from .proto files loaded at runtime, so there's no need to generate any special code when using this language. Instead, in our example server and client we require the gRPC library, then use its load() method:
  var grpc = require('grpc');
  var hello_proto = grpc.load(PROTO_PATH).helloworld;
  

Ready-to-use precompiled versions of protoc and grpc_csharp_plugin binaries for Windows, Linux and Mac OS X are available in the Grpc.Tools NuGet package (there are platform-specific subdirectories 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.

To generate the code, run the following command from the `examples/csharp/helloworld` directory:

  • Windows
      > packages\Grpc.Tools.0.14.0\tools\windows_x86\protoc.exe -I../../protos --csharp_out Greeter --grpc_out Greeter ../../protos/helloworld.proto --plugin=protoc-gen-grpc=packages\Grpc.Tools.0.14.0\tools\windows_x86\grpc_csharp_plugin.exe 
    
  • Linux (or Mac OS X by using `macosx_x64` directory).
      $ packages/Grpc.Tools.0.14.0/tools/linux_x64/protoc -I../../protos --csharp_out Greeter --grpc_out Greeter ../../protos/helloworld.proto --plugin=protoc-gen-grpc=packages/Grpc.Tools.0.14.0/tools/linux_x64/grpc_csharp_plugin
    
Running the appropriate command for your OS regenerates the following files in the Greeter directory:
  • Greeter/Helloworld.cs contains all the protocol buffer code to populate, serialize, and retrieve our request and response message types
  • Greeter/HelloworldGrpc.cs provides generated client and server classes, including:
    • an abstract base class Greeter.GreeterBase to inherit from when defining RouteGuide service implementations
    • a class Greeter.GreeterClient that can be used to access remote RouteGuide instances
For simplicity, we've provided a Podspec file that runs protoc for you with the appropriate plugin, input, and output, and describes how to compile the generated files. You just need to run in examples/objective-c/route_guide:
    $ pod install
    
You can then open the XCode workspace created by Cocoapods to see the generated code. Running the command generates:
  • Helloworld.pbobjc.h, the header which declares your generated message classes.
  • Helloworld.pbobjc.m, which contains the implementation of your message classes.
  • Helloworld.pbrpc.h, the header which declares your generated service classes.
  • Helloworld.pbrpc.m, which contains the implementation of your service classes.
gRPC PHP uses the protoc-gen-php tool to generate code from .proto files. You can find out how to install this in the PHP Quickstart. To generate the code for our Greeter service, run:
  protoc-gen-php -i . -o . ./helloworld.proto
  
This generates helloworld.php, which contains:
  • All the protocol buffer code to populate, serialize, and retrieve our request and response message types.
  • A class called GreeterClient that lets clients call the methods defined in the Greeter service.

Writing a server

Now let’s write some code! First we’ll create a server application to implement our service (which, you’ll remember, we can do in all gRPC languages except Objective-C and PHP). We’re not going to go into a lot of detail about how to create a server in this section - more detailed information will be in the tutorial for your chosen language.

Service implementation

GreeterImpl.java actually implements our Greeter service's required behaviour.</p> As you can see, the class GreeterImpl extends the abstract class GreeterGrpc.GreeterImplBase that we generated from our proto IDL by implementing the method sayHello:</p>
@Override
public void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) {
  HelloReply reply = HelloReply.newBuilder().setMessage("Hello " + req.getName()).build();
  responseObserver.onNext(reply);
  responseObserver.onCompleted();
}
  • sayHello takes two parameters:
    • HelloRequest: the request
    • StreamObserver<HelloReply>: a response observer, which is a special interface for the server to call with its response
To return our response to the client and complete the call:
  1. We construct and populate a HelloReply response object with our exciting message, as specified in our interface definition.
  2. We return the HelloReply to the client and then specify that we've finished dealing with the RPC.
greeter_server.cc implements our Greeter service's required behaviour. As you can see, the class GreeterServiceImpl implements the interface Greeter::Service that we generated from our proto service definition by implementing the method sayHello:
class GreeterServiceImpl final : public Greeter::Service {
  Status SayHello(ServerContext* context, const HelloRequest* request,
                  HelloReply* reply) override {
    std::string prefix("Hello ");
    reply->set_message(prefix + request->name());
    return Status::OK;
  }
};
In this case we're implementing the synchronous version of Greeter, which provides our default gRPC server behaviour (there's also an asynchronous interface, Greeter::AsyncService).
  • sayHello takes three parameters:
    • ServerContext: a context object for this RPC.
    • HelloRequest: the request
    • HelloReply: the response
To return our response to the client and complete the call:
  1. We populate the provided HelloReply response object with our exciting message, as specified in our interface definition.
  2. We return Status::OK to specify that we've finished dealing with the RPC.
greeter_server.py implements our Greeter service's required behaviour. As you can see, the class Greeter implements the interface helloworld_pb2.BetaGreeterServicer that we generated from our proto service definition by implementing the method SayHello:
class Greeter(helloworld_pb2.BetaGreeterServicer):

  def SayHello(self, request, context):
    return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name)
To return our response to the client and complete the call:
  • We construct and populate a HelloReply response object with our exciting message, as specified in our interface definition.
  • We return the HelloReply to the client.
greeter_server/main.go implements our Greeter service's required behaviour. As you can see, our server has a server struct type. This implements the GreeterServer interface that we generated from our proto service definition by implementing the method SayHello:
// server is used to implement helloworld.GreeterServer.
type server struct{}

// SayHello implements helloworld.GreeterServer
func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
	return &pb.HelloReply{Message: "Hello " + in.Name}, nil
}
To return our response to the client and complete the call:
  • We construct and populate a HelloReply response object with our exciting message, as specified in our interface definition.
  • We return the HelloReply to the client.
greeter_server.rb implements our Greeter service's required behaviour. Our server has a GreeterServer class, which implements the GreeterServer interface that we generated from our proto service definition by implementing the method SayHello:
class GreeterServer < Helloworld::Greeter::Service
  # say_hello implements the SayHello rpc method.
  def say_hello(hello_req, _unused_call)
    Helloworld::HelloReply.new(message: "Hello #{hello_req.name}")
  end
To return our response to the client and complete the call, we construct and populate a HelloReply response object with our exciting message, as specified in our interface definition, then return.

greeter_server.js implements our Greeter service's required behaviour. Our server implements the Greeterservice from our service definition by implementing the method SayHello:

function sayHello(call, callback) {
  callback(null, {message: 'Hello ' + call.request.name});
}

To return our response to the client and complete the call, we populate our response and pass it to the provided callback, with a null first parameter to indicate that there is no error.

GreeterServer/Program.cs implements our Greeter service's required behaviour. Our server has a GreeterImpl class, which extends the GreeterBase abstract class that we generated from our proto service definition by implementing the method SayHello:

class GreeterImpl : Greeter.GreeterBase
{
    public override Task<HelloReply> SayHello(HelloRequest request, ServerCallContext context)
    {
        return Task.FromResult(new HelloReply { Message = "Hello " + request.Name });
    }
}
To return our response to the client and complete the call:
  • We construct and populate a HelloReply response object with our exciting message, as specified in our interface definition.
  • We return the HelloReply to the client.

Server implementation

The other main feature required to provide a gRPC service is making the service implementation available from the network.

HelloWorldServer.java provides this for our Java example.
/* The port on which the server should run */
private int port = 50051;
private Server server;

private void start() throws Exception {
  server = ServerBuilder.forPort(port)
      .addService(new GreeterImpl())
      .build()
      .start();
  logger.info("Server started, listening on " + port);
  Runtime.getRuntime().addShutdownHook(new Thread() {
    @Override
    public void run() {
      // Use stderr here since the logger may has been reset by its JVM shutdown hook.
      System.err.println("*** shutting down gRPC server since JVM is shutting down");
      HelloWorldServer.this.stop();
      System.err.println("*** server shut down");
    }
  });
}

greeter_server.cc also provides this for our C++ example.

void RunServer() {
  std::string server_address("0.0.0.0:50051");
  GreeterServiceImpl service;

  ServerBuilder builder;
  builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
  builder.RegisterService(&service);
  std::unique_ptr<Server> server(builder.BuildAndStart());
  std::cout << "Server listening on " << server_address << std::endl;
  server->Wait();
}

greeter_server.py also provides this for our Python example.

  server = helloworld_pb2.beta_create_Greeter_server(Greeter())
  server.add_insecure_port('[::]:50051')
  server.start()
  try:
    while True:
      time.sleep(_ONE_DAY_IN_SECONDS)
  except KeyboardInterrupt:
    server.stop()
greeter_server/main.go also provides this for our Go example.
const (
	port = ":50051"
)
...

func main() {
	lis, err := net.Listen("tcp", port)
	if err != nil {
		log.Fatalf("failed to listen: %v", err)
	}
	s := grpc.NewServer()
	pb.RegisterGreeterServer(s, &server{})
	s.Serve(lis)
}
greeter_server.rb also provides this for our Ruby example.
def main
  s = GRPC::RpcServer.new
  s.add_http2_port('0.0.0.0:50051')
  s.handle(GreeterServer)
  s.run
end
greeter_server.js also provides this for our Node.js example.
function main() {
  var server = new Server({
    "helloworld.Greeter": {
      sayHello: sayHello
    }
  });
  server.bind('0.0.0.0:50051');
  server.listen();
}
GreeterServer/Program.cs also provides this for our C# example.
Server server = new Server
{
    Services = { Greeter.BindService(new GreeterImpl()) },
    Ports = { new ServerPort("localhost", 50051, ServerCredentials.Insecure) }
};
server.Start();

Here we create an appropriate gRPC server, binding the Greeter service implementation that we created to a port. Then we start the server running: the server is now ready to receive requests from Greeter service clients on our specified port. We’ll cover how all this works in a bit more detail in our language-specific documentation.

Writing a client

Client-side gRPC is pretty simple. In this step, we’ll use the generated code to write a simple client that can access the Greeter server we created in the previous section.

Again, we’re not going to go into much detail about how to implement a client; we’ll leave that for the tutorial.

Connecting to the service

First let’s look at how we connect to the Greeter server. First we need to create a gRPC channel, specifying the hostname and port of the server we want to connect to. Then we use the channel to construct the client stub instance.

private final ManagedChannel channel;
private final GreeterGrpc.GreeterBlockingStub blockingStub;

public HelloWorldClient(String host, int port) {
  channel = ManagedChannelBuilder.forAddress(host, port)
      .usePlaintext(true)
      .build();
  blockingStub = GreeterGrpc.newBlockingStub(channel);
}
In this case, we create a blocking stub. This means that the RPC call waits for the server to respond, and will either return a response or raise an exception. gRPC Java has other kinds of stubs that make non-blocking calls to the server, where the response is returned asynchronously.
int main(int argc, char** argv) {
  GreeterClient greeter(
      grpc::CreateChannel("localhost:50051", grpc::InsecureCredentials(),
                          ChannelArguments()));
...
}

...

class GreeterClient {
 public:
  GreeterClient(std::shared_ptr<ChannelInterface> channel)
      : stub_(Greeter::NewStub(channel)) {}
...
 private:
  std::unique_ptr<Greeter::Stub> stub_;
};
The generated Python code has a helper function that creates a stub given a channel.
channel = implementations.insecure_channel('localhost', 50051)
stub = helloworld_pb2.beta_create_Greeter_stub(channel)
...
const (
	address     = "localhost:50051"
	defaultName = "world"
)

func main() {
	// Set up a connection to the server.
	conn, err := grpc.Dial(address, grpc.WithInsecure())
	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}
	defer conn.Close()
	c := pb.NewGreeterClient(conn)
...
}
In gRPC Go you use a special Dial() function to create the channel. This example is not using any authentication, read this document for an explanation of the authentication features of gRPC.
stub = Helloworld::Greeter::Stub.new('localhost:50051', :this_channel_is_insecure)
In Ruby, we can do this in a single method call using the Stub class generated from our .proto.
var client = new hello_proto.Greeter('localhost:50051', grpc.credentials.createInsecure());
In Node.js, we can do this in a single step by calling the Greeter stub constructor.
Channel channel = new Channel("127.0.0.1:50051", Credentials.Insecure);
var client = new Greeter.GreeterClient(channel);
...
In Objective-C, we can do this in a single step using our generated `HLWGreeter` class's designated initializer, which expects a `NSString *` with the server address and port.
#import <GRPCClient/GRPCCall+Tests.h>
...
static NSString * const kHostAddress = @"localhost:50051";
...
[GRPCCall useInsecureConnectionsForHost:kHostAddress];
HLWGreeter *client = [[HLWGreeter alloc] initWithHost:kHostAddress];
Notice the call to `useInsecureConnectionsForHost:`, which tells the gRPC library to use cleartext (instead of TLS-encrypted connections) when communicating with the given host:port pair.
``` $client = new helloworld\GreeterClient( new Grpc\BaseStub('localhost:50051', [])); ``` In PHP, we can do this in a single step using the `GreeterClient` class's constructor.

Calling an RPC

Now we can contact the service and obtain a greeting:

  1. We construct and fill in a HelloRequest to send to the service.
  2. We call the client stub’s SayHello() RPC with our request and get a populated HelloReply if the RPC is successful, from which we can get our greeting.
HelloRequest req = HelloRequest.newBuilder().setName(name).build();
HelloReply reply = blockingStub.sayHello(req);
You can see the complete client code in HelloWorldClient.java.
  std::string SayHello(const std::string& user) {
    HelloRequest request;
    request.set_name(user);
    HelloReply reply;
    ClientContext context;
    Status status = stub_->SayHello(&context, request, &reply);
    if (status.ok()) {
      return reply.message();
    } else {
      return "Rpc failed";
    }
  }
You can see the complete client code in greeter_client.cc.</p>
response = stub.SayHello(helloworld_pb2.HelloRequest(name='you'), _TIMEOUT_SECONDS)
print "Greeter client received: " + response.message
You can see the complete client code in greeter_client.py.</p>
r, err := c.SayHello(context.Background(), &pb.HelloRequest{Name: name})
if err != nil {
		log.Fatalf("could not greet: %v", err)
}
log.Printf("Greeting: %s", r.Message)
You can see the complete client code in greeter_client/main.go.</p>
  message = stub.say_hello(Helloworld::HelloRequest.new(name: user)).message
  p "Greeting: #{message}"
You can see the complete client code in greeter_client.rb.</p>
  client.sayHello({name: user}, function(err, response) {
    console.log('Greeting:', response.message);
  });
You can see the complete client code in greeter_client.js.</p>
var reply = client.SayHello(new HelloRequest { Name = user });
Console.WriteLine("Greeting: " + reply.Message);
You can see the complete example code in GreeterClient/Program.cs.</p>
HLWHelloRequest *request = [HLWHelloRequest message];
request.name = @"Objective-C";
[client sayHelloWithRequest:request handler:^(HLWHelloReply *response, NSError *error) {
  NSLog(@"%@", response.message);
}];
You can see the complete example code in examples/objective-c/helloworld.</p>
  $request = new helloworld\HelloRequest();
  $request->setName($name);
  list($reply, $status) = $client->SayHello($request)->wait();
  $message = $reply->getMessage();
You can see the complete client code in greeter_client.php.</p>

Try it out!

You can try building and running our example using the same language on both the client and server side. Or you can try out one of gRPC’s most useful features - interoperability between code in different languages - and run a server and client in different languages. Each service and client uses interface code generated from the same proto, which means that any Greeter client can talk to any Greeter server.

First run the server:

You can build and run the server from the examples folder. First build the client and server.
$ ./gradlew -PskipCodegen=true installDist
Then run the server, which will listen on port 50051:
$ ./build/install/grpc-examples/bin/hello-world-server
You can build and run the server from the examples/cpp/helloworld folder. First build the client and server.
$ make
Then run the server, which will listen on port 50051:
$ ./greeter_server
You can run the server from examples/python/helloworld using:
$ ./run_server.sh
You can run the server from examples/helloworld using:
$ greeter_server &
You can run the server from examples/ruby using:
$ bundle exec ./greeter_server.rb &
You can run the server from examples/node/dynamic_codegen using:
$ node ./greeter_server.js &
Build the solution. Then from examples/csharp:
> cd GreeterServer/bin/Debug
> GreeterServer.exe

Once the server is running, in another terminal window run the client and confirm that it receives a message.

You can build and run the client from the examples folder. If you haven't already built the client, build it using:
$ ./gradlew -PskipCodegen=true installDist
Then run the client:
$ ./build/install/grpc-examples/bin/hello-world-client
You can build and run the client from the examples/cpp/helloworld folder. If you haven't already built the client, build it using:
$ make
Then run the client:
$ ./greeter_client
You can run the client from examples/python/helloworld using:
$ ./run_client.sh
You can run the client from examples/helloworld using:
$ greeter_client
You can run the client from examples/ruby using:
$ bundle exec ./greeter_client.rb
You can run the client from examples/node/dynamic_codegen using:
$ node ./greeter_client.js
Build the solution. Then from examples/csharp:
> cd GreeterClient/bin/Debug
> GreeterClient.exe
Open the XCode workspace created by Cocoapods, and run the app. You can see the results in XCode's log console.</p>
You can run the client from examples/php using:
$ ./run_greeter_client.sh

Read more!

  • Find out how to install gRPC and get started in each language’s quick start.
  • Follow the tutorial(s) for your favorite language(s).
  • Discover more about gRPC concepts, including RPC life-cycle, synchronous and asynchronous calls, deadlines, and more.
  • Read a detailed description of the gRPC over HTTP2 protocol.
  • gRPC Authentication Support introduces authentication support in gRPC with supported mechanisms and examples.