连接到服务器在qt中失败

时间:2015-07-01 14:55:06

标签: c++ qt

我创建了一个小型服务器/客户端应用程序,为了进行测试,我将服务器/客户端功能放入一个单独的应用程序中。 主要的客户端功能是

Segment              Total                Group
-------------------- -------------------- -----------
1                    7000                 24
2                    7000                 24
3                    7000                 24
4                    7000                 24
5                    7000                 24
6                    645                  24
1                    7000                 55
2                    5400                 55
1                    7000                 41
2                    7000                 41
3                    7000                 41
4                    7000                 41
5                    2000                 41

和服务器功能:

Client::Client(QString purpose) : networkSession(0)
{
    Client::purpose = purpose;
    tcpSocket = new QTcpSocket;
    Client::blockSize = 0;
    connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(readData()));
    connect(tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)),
            this, SLOT(displayError(QAbstractSocket::SocketError)));

    QNetworkConfigurationManager manager;
    if (manager.capabilities() & QNetworkConfigurationManager::NetworkSessionRequired)
    {
        // Get saved network configuration
        QSettings settings(QSettings::UserScope, QLatin1String("QtProject"));
        settings.beginGroup(QLatin1String("QtNetwork"));
        const QString id = settings.value(QLatin1String("DefaultNetworkConfiguration")).toString();
        settings.endGroup();

        // If the saved network configuration is not currently discovered use the system default
        QNetworkConfiguration config = manager.configurationFromIdentifier(id);
        if ((config.state() & QNetworkConfiguration::Discovered) !=
            QNetworkConfiguration::Discovered) {
            config = manager.defaultConfiguration();
        }

        networkSession = new QNetworkSession(config, this);
        connect(networkSession, SIGNAL(opened()), this, SLOT(sessionOpened()));
    }
    qDebug() << "Client set up, waiting";
}

void Client::connectToServer(QString ipAddr, quint32 port)
{
    qDebug() << "Connecting to Host on port " << port << ' ' << (quint16)port;
    tcpSocket->connectToHost(ipAddr, port);
    emit this->connectionResult((tcpSocket->state() == QAbstractSocket::UnconnectedState)?false:true);
    if (tcpSocket->waitForConnected(1000))
        qDebug("Connected!");
    qDebug() << "Am I connected" << tcpSocket->state();
    std::cout << "Am I not connected" << tcpSocket->state();
}

这里的主要问题是,即使我从

获得“已连接”
Server::Server(QString ipAddr, quint32 port, QString purpose)
:  tcpServer(0), networkSession(0)
{
    Server::clientConnection = NULL;
    Server::purpose = purpose;
    Server::port = port;
    QNetworkConfigurationManager manager;
    if (manager.capabilities() & QNetworkConfigurationManager::NetworkSessionRequired) {
        // Get saved network configuration
        QSettings settings(QSettings::UserScope, QLatin1String("QtProject"));
        settings.beginGroup(QLatin1String("QtNetwork"));
        const QString id = settings.value(QLatin1String("DefaultNetworkConfiguration")).toString();
        settings.endGroup();

        // If the saved network configuration is not currently discovered use the system default
        QNetworkConfiguration config = manager.configurationFromIdentifier(id);
        if ((config.state() & QNetworkConfiguration::Discovered) !=
            QNetworkConfiguration::Discovered) {
            config = manager.defaultConfiguration();
        }

        networkSession = new QNetworkSession(config, this);
        connect(networkSession, SIGNAL(opened()), this, SLOT(sessionOpened()));

        //statusLabel->setText(tr("Opening network session."));
        networkSession->open();
    } else {
        sessionOpened();
    }
        //connect(tcpServer, SIGNAL(newConnection()), this, SLOT(sendFortune()));
        connect(tcpServer, SIGNAL(newConnection()), this, SLOT(openNewConnection()));
        //connect(tcpServer, &QTcpServer::newConnection, this, &Server::openNewConnection);
}

void Server::sessionOpened()
{
    // Save the used configuration
    if (networkSession) {
        QNetworkConfiguration config = networkSession->configuration();
        QString id;
        if (config.type() == QNetworkConfiguration::UserChoice)
            id = networkSession->sessionProperty(QLatin1String("UserChoiceConfiguration")).toString();
        else
            id = config.identifier();

        QSettings settings(QSettings::UserScope, QLatin1String("QtProject"));
        settings.beginGroup(QLatin1String("QtNetwork"));
        settings.setValue(QLatin1String("DefaultNetworkConfiguration"), id);
        settings.endGroup();
    }

    tcpServer = new QTcpServer(this);
    if (!tcpServer->listen(QHostAddress::Any, Server::port)) {
        return;
    }
    qDebug() << "Server listening on: " << tcpServer->serverPort();
//! [0]
    QString ipAddress;
    QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();
    // use the first non-localhost IPv4 address
    for (int i = 0; i < ipAddressesList.size(); ++i) {
        if (ipAddressesList.at(i) != QHostAddress::LocalHost &&
            ipAddressesList.at(i).toIPv4Address()) {
            ipAddress = ipAddressesList.at(i).toString();
            break;
        }
    }
    // if we did not find one, use IPv4 localhost
    if (ipAddress.isEmpty())
        ipAddress = QHostAddress(QHostAddress::LocalHost).toString();

//! [1]
}

void Server::openNewConnection(void)
{
    qDebug() << "New conn incoming!";
    Server::clientConnection = tcpServer->nextPendingConnection();
    QVariant ipAddr_QVar(clientConnection->peerAddress().toString());
    qDebug() << "Got new connection!";
    emit gotNewConnection(ipAddr_QVar);
}

在客户端函数中,但服务器函数if (tcpSocket->waitForConnected(1000)) qDebug("Connected!"); qDebug() << "Am I connected" << tcpSocket->state(); 永远不会被调用。为什么?我怎样才能找到这个bug? 如果需要一个最小的工作示例,我可以提供整个代码,但在这里我只想提供最重要的功能。

编辑:
client.h:

openNewConnection()

server.h:

#ifndef CLIENT_H
#define CLIENT_H

//#include <QDialog>
#include <iostream>
#include <QTcpSocket>

class QComboBox;
class QDialogButtonBox;
class QLabel;
class QLineEdit;
class QPushButton;
class QTcpSocket;
class QNetworkSession;

class Client : public QObject
{
    Q_OBJECT
private:
    QTcpSocket *tcpSocket;
    QString currentFortune;
    quint16 blockSize;
    QPair<QString, QPair<QString, QVariant> > data;
    QNetworkSession *networkSession;
    QString purpose;

signals:
    void gotData(QPair<QString, QPair<QString, QVariant> >);
    void noConnection(void);
    void connectionResult(bool);
    void isDisconnect(bool);
public slots:
    void displayError(QAbstractSocket::SocketError socketError);
    void sessionOpened();
    void getInfo();
    void readData();
    void connectToServer(QString ipAddr, quint32 port);
    void disconnectFromServer();
private:

public:


    Client(QString purpose);
};

#endif // CLIENT_H

1 个答案:

答案 0 :(得分:1)

问题在于您的QNetworkSession,您已在范围内声明了它。这意味着一旦你离开该功能,QNetworkSession就会被破坏。被破坏的物体不能发出信号。也许将它作为成员变量或在标题中构造它。