如何在C ++中将元数据添加到流式grpc调用

Rid*_*hod 5 c++ metadata exception 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;
}
Run Code Online (Sandbox Code Playgroud)

服务器端代码:

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");
}
Run Code Online (Sandbox Code Playgroud)

我收到“流中断”异常,因为状态的代码为“ DEADLINE_EXCEEDED”,详细信息为“超过截止期限”。我的ClientContext截止​​期限超时是system_clock :: now()+ 5秒。我究竟做错了什么?

Rid*_*hod 0

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