【问题标题】:How to send byte data over gRPC with C/C++?如何使用 C/C++ 通过 gRPC 发送字节数据?
【发布时间】:2020-12-03 15:57:06
【问题描述】:

所以我使用 gRPC 将数据存储在键值存储中。

原型如下所示:

syntax = "proto3";

package keyvaluestore;

service KeyValueStore {
  rpc AddUser(Credentials) returns (Response) {}
  rpc Get(Request) returns (Response) {}
  rpc Put(Request) returns (Response) {}
  rpc Cput(Request) returns (Response) {}
  rpc Delete(Request) returns (Response) {}
}

message Credentials {
  string user = 1;
  string passwd = 2;
}

message Request {
  string user = 1;
  string key = 2;
  bytes val = 3;
  bytes val2 = 4;
  string addr = 5;
  string command = 6;
}

message Response {
  bytes val = 1;
  uint32 nbytes = 2;
  string message = 3;
}

现在的问题是,如果我们将图像作为字节数据发送过来,其中可以包含空字节,那么当服务器在Request 对象中接收到它时,它会将其视为字符串;当它这样做时,它只会读取第一个空字节。

我们如何在客户端打包Request 对象:

bool KeyValueStoreClient::Put(const string& user, const string& key, const char* val) {
  Request req;
  req.set_user(user);
  req.set_key(key);
  req.set_val(val);

  ClientContext ctx;
  Response res;
  Status status = stub_->Put(&ctx, req, &res);
}

服务器接收req->val() 作为字符串而不是char*

Status KeyValueStoreServiceImpl::Put(ServerContext* ctx, const Request* req, Response* res) {
  // req->val() is a string

}

【问题讨论】:

  • it treats it as a string; when it does this it only reads it up the the first null byte 这不是std::string 的工作方式;它可以在中间包含空字节就好了。

标签: c++ grpc


【解决方案1】:

在您的方法Put 中,val 参数是const char*,而不是std::string

Protobuf documentation for C++ generated code (i.e., the interface to your messages) 表示,当 设置 使用 const char*void set_foo(const char* value) 重载)的值时,它使用第一个 \0 作为终止符。

使用 void set_foo(const char* value, int size) 重载明确告诉它大小。

【讨论】:

  • 你的回答很快就解开了很多信息,很好!从上面关于重载函数的文档中:“字符串大小是明确给出的,而不是通过寻找空终止符字节来确定的”。
猜你喜欢
  • 2011-06-04
  • 1970-01-01
  • 2017-10-09
  • 2011-11-15
  • 1970-01-01
  • 2018-05-23
  • 1970-01-01
  • 2018-07-15
  • 1970-01-01
相关资源
最近更新 更多