0
我试图使用this C++类作为我自己应用程序的客户端/服务器通信的基础。客户端和服务器都有一个“人”类,我想序列:通过套接字发送boost序列化时,应用程序崩溃
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
我不得不把它评论出来,崩溃并不令人惊讶。只要看看服务器发回了什么。
正如你所看到的,每个I型的getObject时,服务器会发送:
22
serialization::archive
9
0
0
31
然后它开始。所以我猜应用程序崩溃了,因为它没有收到完整的序列化对象。我也不知道这些数字大部分在那里做什么,以及为什么他们被一一发送。
我在做什么错?
感谢refp,像一个魅力工作..不能相信我一直在搞这些琐碎的事情; O – natli 2011-12-14 13:53:10