Skip to content

Instantly share code, notes, and snippets.

Last active September 27, 2018 15:13
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Using keepalive based channel connectivity checks and TCP_USER_TIMEOUT to avoid blocking:
import grpc
import time
import helloworld_pb2
import helloworld_pb2_grpc
def run():
channel_opts = [
# Interval at which grpc will send keepalive pings
# Amount of time grpc waits for a keepalive ping to be
# acknowledged before deeming the connection unhealthy and closing
# this also sets TCP_USER_TIMEOUT for the underlying socket to this value
channel = grpc.insecure_channel("localhost:1234", options=channel_opts)
stub = helloworld_pb2_grpc.GreeterStub(channel)
while True:
# Some large message
msg = 'Hello' * 100000
# Check that the connectivity state of the channel is connected (2)
# Passing True here tells the channel attempt to connect if disconnected
if channel._channel.check_connectivity_state(True) == 2:
# Make RPC call supplying a sane timeout value
response = stub.SayHello(helloworld_pb2.HelloRequest(name=msg), timeout=0.3)
except RpcError as e:
# Handle timeouts here
# Do something with response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment