簡體   English   中英

使用 C++ 中的協議緩沖區將文件上傳到服務器

[英]Upload File to a server using Protocol Buffer in C++

我的目標是將文件分塊,然后使用流連接將文件發送到使用 gRPC++ 的服務器。 有人可以確認以下代碼是否適用於客戶端嗎?

我的 proto 文件有一個對象“字節”

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

問題是用於此的構造函數需要一個以空字符結尾的字符串,但您的buffer沒有終止符字節(也不能,因為它可能在中間包含\\0字節)。 這可能會導致std::string構造函數在緩沖區的末尾運行以尋找終止符字節。

要解決此問題,請顯式構造具有長度的std::string

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM