我正在按照以下顺序从用C ++编写的客户端发送gRPC消息的同步流:
如果出现客户端错误,我将如何终止此序列并将其指示给服务器?
答案 0 :(得分:1)
您需要先执行client_context.TryCancel(),然后再执行Finish()。有一些例子 https://github.com/grpc/grpc/blob/master/test/cpp/end2end/end2end_test.cc,ClientCancelsRequestStream。我对其进行了调整以使其更接近您的代码。
RequestType request;
ResponseType response;
ClientContext context;
request.set_message("hello");
auto client_writer = stub_->YourRPC(&context, &response);
client_writer->Write(request);
client_writer->Write(request);
client_context.TryCancel();
Status s = client_writer->Finish();
如果取消成功,则s.error_code()== grpc :: StatusCode :: CANCELLED。
这是来自grpc存储库中client_context.h中ClientContext :: TryCancel()的注释:
/// Send a best-effort out-of-band cancel on the call associated with
/// this client context. The call could be in any stage; e.g., if it is
/// already finished, it may still return success.
///
/// There is no guarantee the call will be cancelled.