[英]Upload File to a server using Protocol Buffer in C++
My objective is to chunk a file and then use a streaming connection to send the file to a server using gRPC++.我的目标是将文件分块,然后使用流连接将文件发送到使用 gRPC++ 的服务器。 Can somebody confirm whether the below code works for the client?
有人可以确认以下代码是否适用于客户端吗?
My proto file has a single object "bytes"我的 proto 文件有一个对象“字节”
message FileContent {
bytes content = 1;
}
Client Code客户代码
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);
}
Server Code服务器代码
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;
}
The protobuf bytes
type generates a field of type std::string
on the C++ side. protobuf
bytes
类型在 C++ 端生成一个std::string
类型的字段。 Your char *buffer
is thus implicitly converted to an std::string
.因此,您的
char *buffer
被隐式转换为std::string
。
The problem is that the constructor used for this expects a null-terminated string, but your buffer
does not have a terminator byte (nor can it, because it may contain \\0
bytes in the middle).问题是用于此的构造函数需要一个以空字符结尾的字符串,但您的
buffer
没有终止符字节(也不能,因为它可能在中间包含\\0
字节)。 This may cause the std::string
constructor to run over the end of the buffer looking for the terminator byte.这可能会导致
std::string
构造函数在缓冲区的末尾运行以寻找终止符字节。
To fix this, construct the std::string
with a length explicitly:要解决此问题,请显式构造具有长度的
std::string
:
filecontent.set_content(std::string(buffer, 2048));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.