我尝试使用this C ++类作为我自己的应用程序客户端/服务器通信的基础。客户和服务器都有“人”。我要序列化的类:
class person
{
public:
person()
{
}
person(int age)
: age_(age)
{
}
int age() const
{
return age_;
}
private:
friend class boost::serialization::access;
template <typename Archive>
void serialize(Archive &ar, const unsigned int version)
{
ar & age_;
}
int age_;
};
我正在尝试在服务器上对其进行序列化和对象,将该序列化发送到客户端,并在那里创建一个新对象。
服务器
while(1)
{
string clientMessageIn = "";
// receive from the client
int numBytes = client->recieveMessage(clientMessageIn);
if ( numBytes == -99 ) break;
if(clientMessageIn == "getObject") //Client asked for object
{
boost::archive::text_oarchive oa(ss);
person pi(31); //Create 31 year old person
oa << pi; //Serialize
std::string mystring;
ss >> mystring; //Serialization to string so we can send it
string sendMsg(mystring); //Set sendMsg (redundant.. probably)
mystring.clear(); //No longer need mystring
client->sendMessage(sendMsg); //Send the actual response to the client
sendMsg.clear(); //Clear
ss.clear(); //Clear
}
else //Client typed something else, just show it
cout << "[RECV:" << clientHost << "]: " << clientMessageIn << endl;
}
客户端
int recvBytes = 0;
while (1)
{
// send message to server
char sendmsg[MAX_MSG_LEN+1];
memset(sendmsg,0,sizeof(sendmsg));
cout << "[" << localHostName << ":SEND] ";
cin.getline(sendmsg,MAX_MSG_LEN);
string sendMsg(sendmsg);
if ( sendMsg.compare("Bye") == 0 || sendMsg.compare("bye") == 0 ) break;
myClient.sendMessage(sendMsg);
// receive response from server
string clientMessageIn = "";
recvBytes = myClient.recieveMessage(clientMessageIn);
if ( recvBytes == -99 ) break;
//stringstream ss;
//ss << clientMessageIn; //Server response to ss
//boost::archive::text_iarchive ia(ss); //This bit is causing the crash
//person p;
//ia >> p; //Unserialize
//ss.clear(); //No longer need the ss contents
//cout << "[RECV:" << serverName << "]: " << p.age<< endl; //This doesn't work now
cout << "[RECV:" << serverName << "]: " << clientMessageIn << endl;
}
boost::archive::text_iarchive ia(ss);
导致崩溃; boost::archive::archive_exception at memory location
我不得不评论它,崩溃并不令人惊讶。只需看看服务器发回的内容。
如您所见,每次输入getObject时,服务器都会发送:
22
serialization::archive
9
0
0
31
然后重新开始。所以我猜应用程序崩溃是因为它没有收到完整的序列化对象。我也不知道大多数这些数字在那里做什么以及为什么它们被逐一发送。
我做错了什么?
答案 0 :(得分:1)
正如您已经指出的那样,您没有发送整个序列化数据缓冲区。
std::string mystring;
ss >> mystring; //Serialization to string so we can send it
应该变成
std::string mystring (ss.str ());
我们现在将整个序列化内容存储在mystring
中,而不是读取第一个空格。