How to achieve server-side bidirectional flow timeout on message receive in gRPC Python?

Viewed 125

Client send message to the Hello method which is bidirectional flow in grpc service.
Server receive the message from client and reply the HelloReply().

Here is what I would like to do: If server does not receive any message from client within 2 seconds, abort the connection.
I attempt to do that with following codes, but not works...

Help is needed, thanks.

class ServerServicer(service_pb2_grpc.HelloServicer):
    def Hello(self, request_iterator, context: grpc.ServicerContext):
        try:
        #     message_receive_time = time.time()
        #     def timeout():
        #         while True:
        #             if time.time() - message_receive_time > 2:
        #                 context.abort(grpc.StatusCode.DEADLINE_EXCEEDED, 'RPC Time Out!')
        #     timeout_task = threading.Thread(target=timeout)
        #     timeout_task.start()
            for request in request_iterator:
                message_receive_time = time.time()
                yield service_pb2.HelloReply()
        except Exception as error:
            traceback.print_exc()
        # timeout_task.close()
0 Answers
Related