• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2023 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"""gRPC Python helloworld.Greeter client with keepAlive channel options."""
15
16import logging
17from time import sleep
18
19import grpc
20import helloworld_pb2
21import helloworld_pb2_grpc
22
23
24def unary_call(
25    stub: helloworld_pb2_grpc.GreeterStub, request_id: int, message: str
26):
27    print("call:", request_id)
28    try:
29        response = stub.SayHello(helloworld_pb2.HelloRequest(name=message))
30        print(f"Greeter client received: {response.message}")
31    except grpc.RpcError as rpc_error:
32        print("Call failed with code: ", rpc_error.code())
33
34
35def run():
36    """
37    grpc.keepalive_time_ms: The period (in milliseconds) after which a keepalive ping is
38        sent on the transport.
39    grpc.keepalive_timeout_ms: The amount of time (in milliseconds) the sender of the keepalive
40        ping waits for an acknowledgement. If it does not receive an acknowledgment within this
41        time, it will close the connection.
42    grpc.keepalive_permit_without_calls: If set to 1 (0 : false; 1 : true), allows keepalive
43        pings to be sent even if there are no calls in flight.
44    grpc.http2.max_pings_without_data: How many pings can the client send before needing to
45        send a data/header frame.
46    For more details, check: https://github.com/grpc/grpc/blob/master/doc/keepalive.md
47    """
48    channel_options = [
49        ("grpc.keepalive_time_ms", 8000),
50        ("grpc.keepalive_timeout_ms", 5000),
51        ("grpc.http2.max_pings_without_data", 5),
52        ("grpc.keepalive_permit_without_calls", 1),
53    ]
54
55    with grpc.insecure_channel(
56        target="localhost:50051", options=channel_options
57    ) as channel:
58        stub = helloworld_pb2_grpc.GreeterStub(channel)
59        # Should succeed
60        unary_call(stub, 1, "you")
61
62        # Run 30s, run this with GRPC_VERBOSITY=DEBUG GRPC_TRACE=http_keepalive to observe logs.
63        # Client will be closed after receveing GOAWAY from server.
64        for i in range(30):
65            print(f"{i} seconds paased.")
66            sleep(1)
67
68
69if __name__ == "__main__":
70    logging.basicConfig()
71    run()
72