在 C++ 中使用 Protocol Buffer 将文件上传到服务器

Upload File to a server using Protocol Buffer in C++

我的 objective 是分块文件,然后使用流连接将文件发送到使用 gRPC++ 的服务器。有人可以确认以下代码是否适用于客户端吗?

我的原型文件只有一个对象"bytes"

message FileContent {
  bytes content = 1;
}

客户代码

char *buffer = new char[2048];
// Open a stream-based connection with the gRPC server
std::unique_ptr<ClientWriter<FileContent> > writer(this->service_stub->Store(&context, &fileack));

// send the file name to the server
filecontent.set_content(filename);
std::cout << "Client: RPC call with File Name:" << filecontent.content() << endl;
writer->Write(filecontent);

// Get a file handle for the file we want to upload and the file length 

fileStream.open(filename, ios::binary);


while (!fileStream.eof())
{
     std::this_thread::sleep_for(std::chrono::milliseconds(100));
     filecontent.clear_content();
     fileStream.read(buffer,2048);
     filecontent.set_content(std::string(buffer, 2048));
     writer->Write(filecontent);
}

服务器代码

    Status Store(ServerContext* context, ServerReader<FileContent>* reader, FileAck* fileack) override {

 FileContent filecontent;
 ofstream fileStream;
 std::string serverfilepath;

 if (fileStream.is_open())
 {
     std::cout << "Reading Data";
     while (reader->Read(&filecontent))
     {
         std::cout << "Reading Data";
         fileStream << filecontent.mutable_content();
     }

     fileStream.close();
 }

 else
 {
    reader->Read(&filecontent);
    fileStream.open(serverfilepath, ios::binary);
 }

 return Status::OK;

}

protobuf bytes类型在C++端生成一个std::string类型的字段。因此,您的 char *buffer 被隐式转换为 std::string.

问题是用于此的 constructor 需要一个以 null 结尾的字符串,但是您的 buffer 没有终止符字节(也不可能,因为它可能包含 [=16 =] 字节在中间)。这可能会导致 std::string 构造函数 运行 在缓冲区的末尾寻找终止符字节。

要解决此问题,请显式构造具有长度的 std::string

filecontent.set_content(std::string(buffer, 2048));