如何在 C++ 中将元数据添加到流式 grpc 调用
How to add metadata to streaming grpc calls in c++
我正在尝试做如下类似的事情(即使用流式 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");
}
我收到 "Broken stream" 异常,因为状态代码为 "DEADLINE_EXCEEDED",详细信息为 "Deadline Exceeded"。我的 ClientContext 截止时间超时是 system_clock::now() + 5 秒。我究竟做错了什么?
我刚刚删除了这一行 "writer->WaitForInitialMetadata();" 它开始工作了。我认为这一行让客户端等待来自服务器的一些元数据。不过不确定。
我正在尝试做如下类似的事情(即使用流式 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");
}
我收到 "Broken stream" 异常,因为状态代码为 "DEADLINE_EXCEEDED",详细信息为 "Deadline Exceeded"。我的 ClientContext 截止时间超时是 system_clock::now() + 5 秒。我究竟做错了什么?
我刚刚删除了这一行 "writer->WaitForInitialMetadata();" 它开始工作了。我认为这一行让客户端等待来自服务器的一些元数据。不过不确定。