Respond to ctrl+c on client side

pull/19465/head
Richard Belleville 6 years ago
parent 244279cb36
commit b6a5e94f71
  1. 23
      examples/python/cancellation/client.py
  2. 2
      examples/python/cancellation/server.py

@ -22,6 +22,7 @@ import argparse
import datetime
import logging
import time
import signal
import grpc
@ -31,25 +32,27 @@ from examples.python.cancellation import hash_name_pb2_grpc
_DESCRIPTION = "A client for finding hashes similar to names."
_LOGGER = logging.getLogger(__name__)
# Interface:
# Cancel on ctrl+c or an ideal candidate.
_TIMEOUT_SECONDS = 0.05
def run_unary_client(server_target, name, ideal_distance):
# TODO(rbellevi): Cancel on ctrl+c
with grpc.insecure_channel(server_target) as channel:
stub = hash_name_pb2_grpc.HashFinderStub(channel)
while True:
print("Sending request")
future = stub.Find.future(hash_name_pb2.HashNameRequest(desired_name=name,
ideal_hamming_distance=ideal_distance))
# TODO(rbellevi): Do not leave in a cancellation based on timeout.
# That's best handled by, well.. timeout.
def cancel_request(unused_signum, unused_frame):
print("Cancelling request.")
future.cancel()
signal.signal(signal.SIGINT, cancel_request)
while True:
try:
result = future.result(timeout=20.0)
print("Got response: \n{}".format(result))
result = future.result(timeout=_TIMEOUT_SECONDS)
except grpc.FutureTimeoutError:
print("Cancelling request")
future.cancel()
continue
except grpc.FutureCancelledError:
break
print("Got response: \n{}".format(result))
break
def run_streaming_client(target, name, ideal_distance, interesting_distance):

@ -137,9 +137,11 @@ class HashFinder(hash_name_pb2_grpc.HashFinderServicer):
def Find(self, request, context):
stop_event = threading.Event()
def on_rpc_done():
print("Attempting to regain servicer thread.")
stop_event.set()
context.add_callback(on_rpc_done)
candidates = list(_find_secret(request.desired_name, request.ideal_hamming_distance, stop_event))
print("Servicer thread returning.")
if not candidates:
return hash_name_pb2.HashNameResponse()
return candidates[-1]

Loading…
Cancel
Save