如何在出现错误时中止gRPC流并在C++中指示错误



我正在从用C++编写的客户端发送gRPC消息的同步流,顺序如下:

  • 获取到ClientWriter的unique_ptr
  • 根据需要多次使用消息调用其Write()方法
  • 调用其WritesDone()方法
  • 调用Finish()获取服务器的状态

如果出现客户端错误,我将如何中止此序列并将其指示给服务器?

您需要先执行client_context.TryCancel(),然后执行Finish()。中有一些示例https://github.com/grpc/grpc/blob/master/test/cpp/end2end/end2end_test.cc,客户端取消请求流。我对它进行了调整,使其看起来更接近您的代码。

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.

最新更新