1.proto

  1. syntax = "proto3";
  2. option go_package = ".;proto";
  3. //The greeting service definition
  4. service Greeter{
  5. //Sends a greeting
  6. rpc SayHello(HelloRequest) returns (HelloReply);
  7. }
  8. //The request message containing the user's name.
  9. message HelloRequest{
  10. string name = 1;
  11. }
  12. //The response message containing the greetings
  13. message HelloReply{
  14. string message = 1;
  15. }

2.server

  1. from __future__ import print_function
  2. from concurrent import futures
  3. import logging
  4. import grpc
  5. import helloworld_pb2
  6. import helloworld_pb2_grpc
  7. class Greeter(helloworld_pb2_grpc.GreeterServicer):
  8. def SayHello(self, request, context):
  9. for key, value in context.invocation_metadata():
  10. print('Received initial metadata: key=%s value=%s' % (key, value))
  11. return helloworld_pb2.HelloReply(message='Hello,%s!' % request.name)
  12. def serve():
  13. server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
  14. helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)
  15. server.add_insecure_port('[::]:50051')
  16. server.start()
  17. server.wait_for_termination()
  18. if __name__ == '__main__':
  19. logging.basicConfig()
  20. serve()

3.client

  1. from __future__ import print_function
  2. import logging
  3. import grpc
  4. import helloworld_pb2
  5. import helloworld_pb2_grpc
  6. def run():
  7. # NOTE(gRPC Python Team): .close() is possible on a channel and should be
  8. # used in circumstances in which the with statement does not fit the needs
  9. # of the code.
  10. with grpc.insecure_channel('localhost:50051') as channel:
  11. stub = helloworld_pb2_grpc.GreeterStub(channel)
  12. response, call = stub.SayHello.with_call(
  13. helloworld_pb2.HelloRequest(name='you'),
  14. metadata=(
  15. ('name', 'golang'),
  16. ('password', 'jetbrains')
  17. )
  18. )
  19. print("Greeter client received: " + response.message)
  20. if __name__ == '__main__':
  21. run()