mak*_*ake 2 c c++ sockets networking protocol-buffers
我试图通过套接字发送一个原型,但我得到分段错误.有人可以帮忙告诉我这个例子有什么问题吗?
file.proto
message data{
required string x1 = 1;
required uint32 x2 = 2;
required float x3 = 3;
}
Run Code Online (Sandbox Code Playgroud)
xxx.cpp
...
data data_snd, data_rec;
//sending data to the server
if (send(socket, &data_snd, sizeof(data_snd), 0) < 0) {
cerr << "send() failed" ;
exit(1);
}
//receiving data from the client
if (recv(socket, &data_rec, sizeof(data_rec), 0) < 0) {
cerr << "recv() failed";
exit(1);
}
Run Code Online (Sandbox Code Playgroud)
感谢您的帮助和回复 -
您不应该将protobuf对象本身写入套接字.使用SerializeXXX方法系列来获取可以写入套接字的字节序列.
std::string buf;
data.SerializeToString(&buf);
// now you can write buf.data() to the socket
Run Code Online (Sandbox Code Playgroud)
首先,您假设一次调用recv将检索所有数据.更重要的是,您没有经历序列化/反序列化代码 - 您只是从网络中读取并将字节直接放入对象中.您应该使用Protocol Buffers中的基于流的API来编写和读取数据.
有关更多详细信息,请参阅Protocol Buffers C++教程 - 这给出了保存到磁盘的示例,但我希望网络版本类似,只是使用不同的流.