即使我明确连接到服务器,在QTcpSever中也不会发出newConnection()信号

时间:2014-08-16 16:29:31

标签: c++ qt networking tcp network-programming

QTcpServer应该在收到新的客户端连接时发出newConnection()信号。我能够连接到我创建的服务器,甚至telnet到它。但是在服务器实现中,我已将newConnection()信号连接到一个插槽,它永远不会被调用。

请你看看我的代码并告诉我,我做错了什么?

首先是标题:

#include <data_model.pb.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <QtNetwork>
#include <QVector>
#include <iostream>
#include <QAbstractSocket>
#include <QDebug>

class QTcpServer;
class QNetworkSession;

class superServer : public QObject
{
    Q_OBJECT

public:

    explicit superServer(QObject *parent = 0);
    data_model::terminal_data fetch_next_record();
    void route_data();

private slots:
    void sessionOpened();

public slots:
    void newTerminalConnection();
    void errorconnecting(QAbstractSocket::SocketError socketError);

private:
    QTcpServer *tcpServer;
    QNetworkSession *networkSession;
    QVector<QTcpSocket*> liveConnections;
};


#endif // SUPERSERVER_HPP

现在实施:

#include <superServer.hpp>

void superServer::newTerminalConnection()
{
    qDebug() << "someone connected ...";
    std::cout << "someone connected ..." << std::endl;
    QTcpSocket *socket = tcpServer->nextPendingConnection();
    liveConnections.push_back(socket);
}

superServer::superServer(QObject *parent)  :
    QObject(parent)
{
    tcpServer = new QTcpServer();

    if(!tcpServer->listen(QHostAddress::Any, 9889))
        qDebug() << "Server could not start";
    else
        qDebug() << "Server started!";

    connect(tcpServer, SIGNAL(newConnection()), this, SLOT(newTerminalConnection()));
    connect(tcpServer, SIGNAL(acceptError(QAbstractSocket::SocketError)), this, SLOT(errorconnecting(QAbstractSocket::SocketError)));
}

void superServer::errorconnecting(QAbstractSocket::SocketError socketError)
{
    qDebug() << "error connecting to client";
}

另外,我这样连接:

void tradeView::doConnect()
{
    socket = new QTcpSocket(this);

    connect(socket, SIGNAL(connected()),this, SLOT(connected()));
    connect(socket, SIGNAL(disconnected()),this, SLOT(disconnected()));
    connect(socket, SIGNAL(bytesWritten(qint64)),this, SLOT(bytesWritten(qint64)));
    connect(socket, SIGNAL(readyRead()),this, SLOT(readyRead()));

    qDebug() << "connecting...";

    // this is not a blocking call
    socket->connectToHost("localhost", 9889);

    // we need to wait...
    if(!socket->waitForConnected(5000))
    {
        qDebug() << "Error: " << socket->errorString();
    }
}

void tradeView::connected()
{
    qDebug() << "connected...";
}

void tradeView::disconnected()
{
    qDebug() << "disconnected...";
}

void tradeView::bytesWritten(qint64 bytes)
{
    qDebug() << bytes << " bytes written...";
}

客户连接!!!即使是Telnet也能工作!

但是那个信号没有被发出。你能告诉我出了什么问题吗?

相信我,我已经在SO和qt-center上查看了十几个相关的主题。没有给出解决方案。 请帮忙。

0 个答案:

没有答案