如何在c ++中

时间:2016-08-11 00:12:02

标签: c++ exception metadata grpc

我正在尝试做类似下面的事情(即使用流式grpc调用从客户端向服务器发送数据)。代码参考取自官方网站上给出的grpc示例,用于解释目的:

客户端代码:

ClientContext context;
context.AddMetadata("authorization", "abcd");
context.set_deadline(...);

std::unique_ptr<ClientWriter<RequestObjectClass>> writer(stub_->grpcCall(&context, &response));
writer->WaitForInitialMetadata();

// Setting request parameters
request.set...(...);
request.set...(...);
request.set...(...);
request.set...(...);

if (!writer->Write(request)) {
    Status status = writer->Finish();
    if (status.error_code() == UNAUTHENTICATED) {
        std::cout << "UNAUTHORIZED" << std::endl;
        break;
    }

    // Broken stream.
    throw Exception("Broken Stream");
}

writer->WritesDone();
Status status = writer->Finish();
if (status.ok()) {
    std::cout << "RPC succeeded." << std::endl;
} else {
    std::cout << "RPC failed." << std::endl;
}

服务器端代码:

std::multimap<grpc::string_ref, grpc::string_ref> metadata = context->client_metadata();
auto auth = metadata.find("authorization");

if (auth == metadata.end()) {
    return Status(StatusCode::UNAUTHENTICATED, "UNAUTHORIZED");
}

我得到了#34; Broken stream&#34;异常,因为状态有代码&#34; DEADLINE_EXCEEDED&#34;详情为&#34;截止日期超过&#34;。我对ClientContext的截止时间超时是system_clock :: now()+ 5秒。我究竟做错了什么?

1 个答案:

答案 0 :(得分:0)

我刚删除了这一行“writer-&gt; WaitForInitialMetadata();”它开始工作了。我认为这一行使客户端等待来自服务器的一些元数据。但不确定。