asyncio_send_message.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. # Copyright 2020 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. import argparse
  16. import asyncio
  17. import logging
  18. import grpc
  19. helloworld_pb2, helloworld_pb2_grpc = grpc.protos_and_services(
  20. "helloworld.proto")
  21. async def process(stub: helloworld_pb2_grpc.GreeterStub,
  22. request: helloworld_pb2.HelloRequest) -> None:
  23. try:
  24. response = await stub.SayHello(request)
  25. except grpc.aio.AioRpcError as rpc_error:
  26. print(f'Received error: {rpc_error}')
  27. else:
  28. print(f'Received message: {response}')
  29. async def run(addr: str, n: int) -> None:
  30. async with grpc.aio.insecure_channel(addr) as channel:
  31. stub = helloworld_pb2_grpc.GreeterStub(channel)
  32. request = helloworld_pb2.HelloRequest(name='you')
  33. for _ in range(n):
  34. await process(stub, request)
  35. async def main() -> None:
  36. parser = argparse.ArgumentParser()
  37. parser.add_argument('--addr',
  38. nargs=1,
  39. type=str,
  40. default='[::]:50051',
  41. help='the address to request')
  42. parser.add_argument('-n',
  43. nargs=1,
  44. type=int,
  45. default=10,
  46. help='an integer for number of messages to sent')
  47. args = parser.parse_args()
  48. await run(addr=args.addr, n=args.n)
  49. if __name__ == '__main__':
  50. logging.basicConfig(level=logging.INFO)
  51. asyncio.get_event_loop().run_until_complete(main())