send_message.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. # Copyright 2019 The gRPC Authors
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """Send multiple greeting messages to the backend."""
  15. from __future__ import absolute_import
  16. from __future__ import division
  17. from __future__ import print_function
  18. import argparse
  19. import logging
  20. import grpc
  21. helloworld_pb2, helloworld_pb2_grpc = grpc.protos_and_services(
  22. "helloworld.proto")
  23. def process(stub, request):
  24. try:
  25. response = stub.SayHello(request)
  26. except grpc.RpcError as rpc_error:
  27. print('Received error: %s' % rpc_error)
  28. else:
  29. print('Received message: %s' % response)
  30. def run(addr, n):
  31. with grpc.insecure_channel(addr) as channel:
  32. stub = helloworld_pb2_grpc.GreeterStub(channel)
  33. request = helloworld_pb2.HelloRequest(name='you')
  34. for _ in range(n):
  35. process(stub, request)
  36. def main():
  37. parser = argparse.ArgumentParser()
  38. parser.add_argument('--addr',
  39. nargs=1,
  40. type=str,
  41. default='[::]:50051',
  42. help='the address to request')
  43. parser.add_argument('-n',
  44. nargs=1,
  45. type=int,
  46. default=10,
  47. help='an integer for number of messages to sent')
  48. args = parser.parse_args()
  49. run(addr=args.addr, n=args.n)
  50. if __name__ == '__main__':
  51. logging.basicConfig()
  52. main()