我使用c ++的协议缓冲区来生成应该通过网络发送的字符串。但是在致电ParseFromString
时,我收到false
作为回复而没有错误消息!?
我按如下方式创建要发送的对象:
Messages::RequestMessage msg;
msg.set_type(1);
msg.set_epid(4);
string s;
if (msg.SerializeToString(&s)) {
Log("serialized");
return s;
} else {
Log("error serializing", log::error);
return "";
}
现在应该通过网络从boost :: asio通过async_write
发送生成的字符串。我在这里尝试了不同的方法:
max_length = 1024;
char data_[max_length];
memset(data_, '\0', sizeof(char)*max_length);
//first tried
//const char *msg = s.c_str();
//memcpy(data_, msg, strlen(msg));
memcpy(data_, s.data(), s.size());
boost::asio::async_write(socket_, boost::asio::buffer(data_, max_length),
boost::bind(&Session::handle_write, this,
boost::asio::placeholders::error));
在接收方:
char reply_[max_length];
boost::asio::async_read(socket_, boost::asio::buffer(reply_, max_length),
boost::bind(&Client::handle_read, this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
string str(reply_);
Messages::RequestMessage m;
bool ret = m.ParseFromString(str);
//which gives ret=false but no error msg is displayed!?
我认为将字符串转换为char *并返回可能有问题吗?