退出程序时删除对象

时间:2017-10-30 12:31:36

标签: c++ qt

我有一个简单的客户端 - 服务器qt程序。在程序结束时,我希望客户端将一些设置发送到服务器,以便他保存它们。

void Client::closeEvent(QCloseEvent* event)
{
finishSession();
event->accept();
}


void Client::finishSession()
{
QByteArray* array = new QByteArray;
QDataStream in(array, QIODevice::WriteOnly);
in.setVersion(QDataStream::Qt_5_9);

in << quint16(6) << m_name << quint16(vecContacts.size());
for (int i=0; i<vecContacts.size(); i++)
{
    in << vecContacts[i]->checkName();
}
for (int i=0; i<vecContacts.size(); i++)
{
    in << vecContacts[i]->getText();
}
pClientSocket->write(*array);
}

但是,当我将数据放入流服务器时,无论如何都不会对此做出反应,尽管在程序期间一切正常。 我认为发生这种情况是因为当我关闭Client小部件时服务器类的对象被破坏(服务器对象始终是hiden)。但我既不确定也不知道如何解决这个问题。我的功能主要:

int main(int argc, char *argv[])
{
QApplication app(argc, argv);

Server* m_pServer = new Server;
cout << "Server port is " << m_pServer->getServerPort() << endl;


Client* p1Client = new Client (m_pServer->getServerPort() );
p1Client->show();
m_pServer->show();


return app.exec();
}

我是否正确删除服务器对象?如果是这样如何解决?

发现如果我在main函数中显示我的服务器对象,一切正常

与该问题有关的服务器代码的一部分:

void Server::slotReadyRead()
{
cout << "server slotReadyRead" << endl;
QTcpSocket* senSocket = (QTcpSocket*)sender();
QDataStream out(senSocket);
quint16 var = 0;
out >> var;
switch (var)
{
case 5:
    cout << "MESSAGE RECEIVED" << endl;
    getMessage(senSocket);
    break;
case 1:
    logName(senSocket );
    break;
case 2:
    logPass(senSocket);
    break;
case 3:
    newAccount(senSocket);
    break;
case 4:
    newContact(senSocket);
    break;
case 6:
    saveAccountSettings(senSocket);
    break;
case 7:
    openAccountSettings(senSocket);
    break;
}
}

void Server::saveAccountSettings(QTcpSocket* sender)
{
cout << "Server saving setting" << endl;
QDataStream out(sender);
QString acName;
QString contacts("");
QString add;
// read account name
out >> acName;
quint16 num;
//read number of contacts
out >> num;
// read first contact name
out >> add;
contacts = add;
QStringList list;
for (int i = 1; i < num; i++)
{
    out >> add;
    list.append(add);
    contacts += ("+" + add);
}
QSettings settings("Chat", "Server");
settings.setValue("/settings/" + acName + "/contacts", contacts);

for (int i=0; i<num; i++)
{
    add = list[i];
    out >> contacts;
    settings.setValue("/settings/" +acName + "/" + add, contacts);
}
cout << "Server saved settings" << endl;

}

0 个答案:

没有答案