1.proto
syntax = "proto3";option go_package = ".;proto";//The greeting service definitionservice Greeter{//Sends a greetingrpc SayHello(HelloRequest) returns (HelloReply);}//The request message containing the user's name.message HelloRequest{string name = 1;}//The response message containing the greetingsmessage HelloReply{string message = 1;}
2.server
from __future__ import print_functionfrom concurrent import futuresimport loggingimport grpcimport helloworld_pb2import helloworld_pb2_grpcclass Greeter(helloworld_pb2_grpc.GreeterServicer): def SayHello(self, request, context): for key, value in context.invocation_metadata(): print('Received initial metadata: key=%s value=%s' % (key, value)) return helloworld_pb2.HelloReply(message='Hello,%s!' % request.name) def serve(): server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server) server.add_insecure_port('[::]:50051') server.start() server.wait_for_termination()if __name__ == '__main__': logging.basicConfig() serve()
3.client
from __future__ import print_functionimport loggingimport grpcimport helloworld_pb2import helloworld_pb2_grpcdef run(): # NOTE(gRPC Python Team): .close() is possible on a channel and should be # used in circumstances in which the with statement does not fit the needs # of the code. with grpc.insecure_channel('localhost:50051') as channel: stub = helloworld_pb2_grpc.GreeterStub(channel) response, call = stub.SayHello.with_call( helloworld_pb2.HelloRequest(name='you'), metadata=( ('name', 'golang'), ('password', 'jetbrains') ) ) print("Greeter client received: " + response.message)if __name__ == '__main__': run()