我正在尝试做类似下面的事情(即使用流式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 …Run Code Online (Sandbox Code Playgroud)