xref: /aosp_15_r20/external/grpc-grpc/examples/python/debug/send_message.py (revision cc02d7e222339f7a4f6ba5f422e6413f4bd931f2)
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
16from __future__ import absolute_import
17from __future__ import division
18from __future__ import print_function
19
20import argparse
21import logging
22
23import grpc
24
25helloworld_pb2, helloworld_pb2_grpc = grpc.protos_and_services(
26    "helloworld.proto"
27)
28
29
30def process(stub, request):
31    try:
32        response = stub.SayHello(request)
33    except grpc.RpcError as rpc_error:
34        print("Received error: %s" % rpc_error)
35    else:
36        print("Received message: %s" % response)
37
38
39def run(addr, n):
40    with grpc.insecure_channel(addr) as channel:
41        stub = helloworld_pb2_grpc.GreeterStub(channel)
42        request = helloworld_pb2.HelloRequest(name="you")
43        for _ in range(n):
44            process(stub, request)
45
46
47def main():
48    parser = argparse.ArgumentParser()
49    parser.add_argument(
50        "--addr",
51        nargs=1,
52        type=str,
53        default="[::]:50051",
54        help="the address to request",
55    )
56    parser.add_argument(
57        "-n",
58        nargs=1,
59        type=int,
60        default=10,
61        help="an integer for number of messages to sent",
62    )
63    args = parser.parse_args()
64    run(addr=args.addr, n=args.n)
65
66
67if __name__ == "__main__":
68    logging.basicConfig()
69    main()
70