gRPC is a modern, open-source, general-purpose remote procedure call (RPC) framework developed by Google. It enables applications written in different languages and running on different platforms to communicate easily. gRPC uses Protocol Buffers (protobuf) as its default serialization protocol.
Key concepts:
Create a virtual environment:
python -m virtualenv ./venv
Then activate it:
./venv/Scripts/activate
Install the required dependencies:
python -m pip install grpcio python -m pip install grpcio-tools
Create the `./proto` directory and add the IDL file named helloworld.proto
:
syntax = "proto3"; // The greeting service definition. service Greeter { // Sends a greeting rpc SayHello (HelloRequest) returns (HelloReply) {} // Sends another greeting rpc SayHelloAgain (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; }
Run the stub generator with the following command:
python -m grpc_tools.protoc -I ./protos/ --grpc_python_out=. --python_out=. .\protos\helloworld.proto
The files helloworld_pb2.py
and helloworld_pb2_grpc.py
will be generated in the root folder.
The client and server code is as follows:
greeter_client.py
import grpc import helloworld_pb2 import helloworld_pb2_grpc def run(): print("Will try to greet world ...") with grpc.insecure_channel("localhost:50051") as channel: stub = helloworld_pb2_grpc.GreeterStub(channel) response = stub.SayHello(helloworld_pb2.HelloRequest(name="you")) print("Greeter client received: " + response.message) if __name__ == "__main__": run()
greeter_server.py
from concurrent import futures import grpc import helloworld_pb2 import helloworld_pb2_grpc class Greeter(helloworld_pb2_grpc.GreeterServicer): def SayHello(self, request, context): return helloworld_pb2.HelloReply(message="Hello, %s!" % request.name) def serve(): port = "50051" server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server) server.add_insecure_port("[::]:" + port) server.start() print("Server started, listening on " + port) server.wait_for_termination() if __name__ == "__main__": serve()
Start the server and the client.