gpt4 book ai didi

c++ - 通过套接字发送 boost 序列化时应用程序崩溃

转载 作者:行者123 更新时间:2023-11-28 08:12:58 25 4
gpt4 key购买 nike

我正在尝试使用 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 在内存位置

我不得不将其注释掉,崩溃并不令人惊讶。只需看看服务器发回的内容即可。

client

如您所见,每次我键入 getObject 时,服务器都会发送:

22
serialization::archive
9
0
0
31

然后它重新开始。所以我猜应用程序崩溃是因为它没有收到完整的序列化对象。我也不知道这些数字中的大多数在那里做什么,也不知道为什么要将它们一个接一个地发送。

我做错了什么?

最佳答案

正如您已经指出的,您并未发送整个序列化数据缓冲区。

    std::string mystring;
ss >> mystring; //Serialization to string so we can send it

应该变成

    std::string mystring (ss.str ());

我们现在将整个序列化内容存储在 mystring 中,而不是读取第一个空格。

关于c++ - 通过套接字发送 boost 序列化时应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8505270/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com