从单个emit语句多次调用Qt5槽

时间:2013-07-15 14:51:25

标签: qt qt5 signals-slots qudpsocket

我对Qt比较陌生,但我做了一些搜索。我有一个处理UDP广播的基类,并在类的构造函数中执行connect语句,如下所示:

NetworkConnection::NetworkConnection(QObject *parent)
    : QObject(parent) // Based on QObject
    , m_server_search( new QUdpSocket ) // Our UDP Broadcast socket
    , m_waiting_for_server( false )
    , m_found_server( false )
{
    qDebug() << "NetworkConnection::constructor";
    connect( m_server_search, SIGNAL(readyRead()), this, SLOT(serverResponse()), Qt::UniqueConnection );
    if ( m_server_search->bind( QHostAddress::AnyIPv4, (quint16)PORT_MULTICAST, QUdpSocket::ShareAddress ) )
    {
        if ( m_server_search->joinMulticastGroup( QHostAddress( MULTICAST_GROUP ) ) )
        {
            connect( this, SIGNAL(broadcast(NetworkMessage)), this, SLOT(broadcast_message(NetworkMessage)), Qt::UniqueConnection );
            this->m_ping_timer = this->startTimer(2000);
            qDebug() << "Ping timer id=" << this->m_ping_timer;
        } else qDebug() << "Couldn't start multicast listener";
    } else qDebug() << "Couldn't bind multicast to port" << PORT_MULTICAST;
}

我为广播设置了信号/插槽接口:

signals:
    void serverFound();
    void serverNotFound();
    void broadcast(NetworkMessage);

private slots:
    void serverResponse();
    void broadcast_message( NetworkMessage msg );

broadcast_message看起来像这样:

void NetworkConnection::broadcast_message( NetworkMessage msg )
{
    QByteArray raw = msg.toString();
    qDebug() << "NetworkConnection::broadcast_message>" << raw;
    if ( m_server_search->writeDatagram( raw.data(), raw.size(), QHostAddress(MULTICAST_GROUP), (quint16)PORT_MULTICAST ) < 1 ) qDebug() << "Failed broadcast last message";
}

我的计时器工作正常,这是代码:

void NetworkConnection::timerEvent(QTimerEvent *event)
{
    qDebug() << "NetworkConnection::timerEvent with id" << event->timerId() << "(ping timer=" << this->m_ping_timer << ")";
    if ( event->timerId() == this->m_ping_timer )
    {
        qDebug() << "NetworkConnection::pingForServer";
        if ( m_waiting_for_server && !m_found_server )
        {
            qDebug() << "Server not found!";
            emit this->serverNotFound();
            return;
        }
        if ( !m_found_server )
        {
            qDebug() << "Sending a ping to the server";
            NetworkMessage msg( m_software_guid, get_microseconds(), QString("whoisaserver") );
            emit this->broadcast( msg );
            m_waiting_for_server = true;
            m_found_server = false;
        }
    }
}

我只收到一次文本“向服务器发送一个品脱”,但我的broadcast_message多次输出它qDebug()

我没有明确地使用多个线程,你可以看到我正在使用Qt :: UniqueConnection,这显然没有任何影响?

那为什么要多次调用插槽?我甚至尝试过调试它,只是在不使用emit的情况下调用this-&gt; broadcast(...),它仍然会多次调用。

修改:我刚刚在broadcast_message广告位添加了一个计数器,它被调用了340次。这有什么意义吗?

0 个答案:

没有答案