C++ 使用C+中的协议缓冲区将文件上载到服务器+;

C++ 使用C+中的协议缓冲区将文件上载到服务器+;,c++,protocol-buffers,grpc,C++,Protocol Buffers,Grpc,我的目标是将文件分块,然后使用流连接将文件发送到使用gRPC++的服务器。有人能确认以下代码是否适用于客户机吗 我的原型文件只有一个对象“字节” 客户端代码 char *buffer = new char[2048]; // Open a stream-based connection with the gRPC server std::unique_ptr<ClientWriter<FileContent> > writer(this->service_stub-

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

我的原型文件只有一个对象“字节”

客户端代码

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);
}
char*buffer=新字符[2048];
//打开与gRPC服务器的基于流的连接
std::unique_ptr writer(this->service_stub->Store(&context,&fileack));
//将文件名发送到服务器
设置内容(文件名);

STD::CUT< P>原Buff<代码>字节< /Cord>类型生成C++类的代码:<代码> STD::String 。因此,您的
char*缓冲区
被隐式转换为
std::string

问题是,用于此操作的需要以null结尾的字符串,但您的
缓冲区
没有终止符字节(也不能,因为中间可能包含
\0
字节)。这可能会导致
std::string
构造函数在缓冲区的末尾运行,以查找终止符字节

要解决此问题,请使用显式长度构造
std::string

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

非常感谢。感谢。如果这解决了您的问题,请单击复选标记让其他人知道!
    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;

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